<template>
  <div class="elderly-admission-system">
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 步骤导航 - 显示整个入住流程的5个步骤 -->
      <div class="steps-container">
        <div
          v-for="(step, index) in steps"
          :key="step.id"
          :class="[
            'step-item',
            {
              active: currentStep === step.id, // 当前步骤高亮
              completed: step.id < currentStep, // 已完成步骤置为完成状态
              disabled: isStepDisabled(step.id), // 🔥【新增】禁用后续步骤
            },
          ]"
          @click="switchStep(step.id)"
        >
          <div class="step-number">{{ index + 1 }}</div>
          <div class="step-label">{{ step.label }}</div>
          <!-- 步骤间连接线，最后一步不需要 -->
          <div v-if="index < steps.length - 1" class="step-connector"></div>
        </div>
      </div>

      <!-- 操作记录 - 显示流程中的关键操作历史 -->
      <div class="operation-records" v-if="operationRecords.length > 0">
        <h4>操作记录</h4>
        <div class="record-list">
          <div
            v-for="(record, index) in operationRecords"
            :key="index"
            class="record-item"
          >
            <span class="record-content"
              >{{ record.action }} - {{ record.operator }}</span
            >
            <span class="record-time">{{ record.time }}</span>
          </div>
        </div>
      </div>

      <!-- 步骤内容区域 - 根据当前步骤显示对应内容 -->
      <div class="step-content">
        <!-- 1. 申请入住步骤 -->
        <div v-if="currentStep === 1" class="step-panel">
          <div class="panel-header">
            <h2>补全申请资料</h2>
          </div>

          <!-- 标签页导航 - 申请入住包含3个子标签页 -->
          <div class="tab-navigation">
            <div
              v-for="tab in applyTabs"
              :key="tab.id"
              :class="['tab-item', { active: currentApplyTab === tab.id }]"
              @click="switchApplyTab(tab.id)"
            >
              <span class="tab-number">{{ tab.id }}</span>
              <span class="tab-label">{{ tab.label }}</span>
            </div>
          </div>

          <!-- 标签页内容 -->
          <div class="tab-content">
            <!-- 1.1 基本信息 -->
            <div v-if="currentApplyTab === 1" class="tab-panel-content">
              <el-form
                :model="basicForm"
                :rules="rules"
                ref="basicFormRef"
                label-width="120px"
                class="basic-form"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="老人姓名" prop="name" required>
                      <el-input
                        v-model="basicForm.name"
                        placeholder="请输入老人姓名"
                        :maxlength="10"
                        show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="老人身份证号" prop="idCard" required>
                      <el-input
                        v-model="basicForm.idCard"
                        placeholder="请输入老人身份证号"
                        :maxlength="18"
                        show-word-limit
                        @blur="handleIdCardBlur"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="性别" prop="gender">
                      <el-radio-group v-model="basicForm.gender">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="出生日期" prop="birthDate">
                      <el-input
                        v-model="basicForm.birthDate"
                        placeholder="自动识别"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="年龄" prop="age">
                      <el-input
                        v-model="basicForm.age"
                        placeholder="自动计算"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="联系方式" prop="contact" required>
                      <el-input
                        v-model="basicForm.contact"
                        placeholder="请输入联系方式"
                        :maxlength="11"
                        show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="家庭住址" prop="address" required>
                      <el-input
                        v-model="basicForm.address"
                        placeholder="请输入家庭住址"
                        :maxlength="100"
                        show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="民族" prop="ethnicity" required>
                      <el-select
                        v-model="basicForm.ethnicity"
                        placeholder="请选择民族"
                        clearable
                      >
                        <el-option
                          v-for="item in dictData.nationList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="政治面貌" prop="politicalStatus">
                      <el-select
                        v-model="basicForm.politicalStatus"
                        placeholder="请选择政治面貌"
                        clearable
                      >
                        <el-option
                          v-for="item in dictData.politicalList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="宗教信仰" prop="religion">
                      <el-select
                        v-model="basicForm.religion"
                        placeholder="请选择宗教信仰"
                        clearable
                      >
                        <el-option
                          v-for="item in dictData.religionList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="婚姻状况" prop="maritalStatus">
                      <el-select
                        v-model="basicForm.maritalStatus"
                        placeholder="请选择婚姻状况"
                        clearable
                      >
                        <el-option
                          v-for="item in dictData.maritalList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="文化程度" prop="education">
                      <el-select
                        v-model="basicForm.education"
                        placeholder="请选择文化程度"
                        clearable
                      >
                        <el-option
                          v-for="item in dictData.educationList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="经济来源" prop="incomeSource">
                      <el-select
                        v-model="basicForm.incomeSource"
                        placeholder="请选择经济来源"
                        clearable
                      >
                        <el-option
                          v-for="item in dictData.incomeList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="特长爱好" prop="hobbies">
                      <el-select
                        v-model="basicForm.hobbies"
                        placeholder="请选择特长爱好"
                        clearable
                      >
                        <el-option
                          v-for="item in dictData.hobbyList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="医疗保障" prop="medicalInsurance">
                      <el-select
                        v-model="basicForm.medicalInsurance"
                        placeholder="请选择医疗保障"
                        clearable
                      >
                        <el-option
                          v-for="item in dictData.medicalList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="医保卡号">
                      <el-input
                        v-model="basicForm.medicalCardNo"
                        placeholder="请输入医保卡号"
                        :maxlength="19"
                        show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>

            <!-- 1.2 家属信息 -->
            <div v-else-if="currentApplyTab === 2" class="tab-panel-content">
              <div class="family-table">
                <el-table :data="familyForm.members" style="width: 100%">
                  <el-table-column prop="name" label="家属姓名" width="200">
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.name"
                        placeholder="请输入家属姓名"
                        :maxlength="10"
                        show-word-limit
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="contact"
                    label="家属联系方式"
                    width="200"
                  >
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.contact"
                        placeholder="请输入家属联系方式"
                        :maxlength="11"
                        show-word-limit
                      />
                    </template>
                  </el-table-column>

                  <el-table-column
                    prop="relationship"
                    label="与老人关系"
                    width="200"
                  >
                    <template #default="scope">
                      <el-select
                        v-model="scope.row.relationship"
                        placeholder="请选择与老人的关系"
                      >
                        <el-option label="子女" value="children" />
                        <el-option label="配偶" value="spouse" />
                        <el-option label="亲属" value="relative" />
                        <el-option label="朋友" value="friend" />
                        <el-option label="社工" value="socialWorker" />
                        <el-option label="其他" value="other" />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" width="100">
                    <template #default="scope">
                      <el-button
                        link
                        type="danger"
                        @click="removeFamilyMember(scope.$index)"
                        :disabled="familyForm.members.length <= 1"
                      >
                        <el-icon><Minus /></el-icon>
                      </el-button>
                      <el-button link type="primary" @click="addFamilyMember">
                        <el-icon><Plus /></el-icon>
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <!-- 1.3 资料上传 -->
            <div v-else-if="currentApplyTab === 3" class="tab-panel-content">
              <div class="upload-notice">
                <p>图片大小不超过2M，仅支持上传PNG、JPG、JPEG类型图片</p>
              </div>

              <div class="upload-sections">
                <div class="upload-item">
                  <div class="upload-label">
                    <span class="required">*</span>
                    <span>一寸照片</span>
                  </div>
                  <div class="upload-container">
                    <!-- 上传按钮，只在没有文件时显示 -->
                    <el-upload
                      v-if="!photoFiles || photoFiles.length === 0"
                      action="#"
                      :auto-upload="false"
                      :on-change="handlePhotoUpload"
                      :limit="1"
                      accept=".jpg,.jpeg,.png"
                      :show-file-list="false"
                    >
                      <el-button size="large" type="primary">
                        <el-icon><Plus /></el-icon>
                        上传一寸照片
                      </el-button>
                    </el-upload>

                    <!-- 已上传图片显示区域，只在有文件时显示 -->
                    <div v-else class="uploaded-file-display">
                      <!-- 简化处理，直接显示文件名和删除按钮 -->
                      <div
                        class="file-info"
                        @click="previewFile(photoFiles[0])"
                        style="cursor: pointer"
                      >
                        <el-icon><View /></el-icon>
                        <span>{{ photoFiles[0].name }}</span>
                      </div>
                      <el-button type="text" @click="handlePhotoRemove">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                    </div>
                    <div class="el-upload__tip">请上传一寸免冠照片</div>
                  </div>
                </div>

                <div class="upload-item">
                  <div class="upload-label">
                    <span class="required">*</span>
                    <span>身份证人像面</span>
                  </div>
                  <div class="upload-container">
                    <!-- 上传按钮，只在没有文件时显示 -->
                    <el-upload
                      v-if="!idCardFrontFiles || idCardFrontFiles.length === 0"
                      action="#"
                      :auto-upload="false"
                      :on-change="handleIdCardFrontUpload"
                      :limit="1"
                      accept=".jpg,.jpeg,.png"
                      :show-file-list="false"
                    >
                      <el-button size="large" type="primary">
                        <el-icon><Plus /></el-icon>
                        上传身份证人像面
                      </el-button>
                    </el-upload>

                    <!-- 已上传图片显示区域，只在有文件时显示 -->
                    <div v-else class="uploaded-file-display">
                      <!-- 简化处理，直接显示文件名和删除按钮 -->
                      <div
                        class="file-info"
                        @click="previewFile(idCardFrontFiles[0])"
                        style="cursor: pointer"
                      >
                        <el-icon><View /></el-icon>
                        <span>{{ idCardFrontFiles[0].name }}</span>
                      </div>
                      <el-button type="text" @click="handleIdCardFrontRemove">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                    </div>
                    <div class="el-upload__tip">请上传身份证人像面照片</div>
                  </div>
                </div>

                <div class="upload-item">
                  <div class="upload-label">
                    <span class="required">*</span>
                    <span>身份证国徽面</span>
                  </div>
                  <div class="upload-container">
                    <!-- 上传按钮，只在没有文件时显示 -->
                    <el-upload
                      v-if="!idCardBackFiles || idCardBackFiles.length === 0"
                      action="#"
                      :auto-upload="false"
                      :on-change="handleIdCardBackUpload"
                      :limit="1"
                      accept=".jpg,.jpeg,.png"
                      :show-file-list="false"
                    >
                      <el-button size="large" type="primary">
                        <el-icon><Plus /></el-icon>
                        上传身份证国徽面
                      </el-button>
                    </el-upload>

                    <!-- 已上传图片显示区域，只在有文件时显示 -->
                    <div v-else class="uploaded-file-display">
                      <!-- 简化处理，直接显示文件名和删除按钮 -->
                      <div
                        class="file-info"
                        @click="previewFile(idCardBackFiles[0])"
                        style="cursor: pointer"
                      >
                        <el-icon><View /></el-icon>
                        <span>{{ idCardBackFiles[0].name }}</span>
                      </div>
                      <el-button type="text" @click="handleIdCardBackRemove">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                    </div>
                    <div class="el-upload__tip">请上传身份证国徽面照片</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 2. 入住评估步骤 -->
        <div v-else-if="currentStep === 2" class="step-panel">
          <div class="panel-header">
            <h2>健康能力评估</h2>
            <div class="auto-save-status">
              <el-button 
                type="primary" 
                size="small" 
                :loading="isSaving"
                @click="autoSaveAssessmentData(true)"
                icon="DocumentCopy"
              >
                {{ isSaving ? '保存中...' : '手动保存' }}
              </el-button>
              <span v-if="lastAutoSaveTime" class="save-time">
                最后保存: {{ lastAutoSaveTime.toLocaleTimeString() }}
              </span>
            </div>
          </div>

          <!-- 评估标签页 -->
          <div class="tab-navigation">
            <div
              v-for="tab in assessmentTabs"
              :key="tab.id"
              :class="['tab-item', { active: currentAssessmentTab === tab.id }]"
              @click="switchAssessmentTab(tab.id)"
            >
              <span class="tab-number">{{ tab.id }}</span>
              <span class="tab-label">{{ tab.label }}</span>
            </div>
          </div>

          <!-- 评估内容 -->
          <div class="tab-content">
            <!-- 2.1 健康评估 -->
            <div v-if="currentAssessmentTab === 1" class="tab-panel-content">
              <div class="assessment-section">
                <h4>疾病和用药情况</h4>
                <el-form :model="healthForm" label-width="120px">
                  <el-form-item label="疾病诊断" required>
                    <el-checkbox-group v-model="healthForm.diseases">
                      <el-checkbox label="无疾病">无疾病</el-checkbox>
                      <el-checkbox label="冠心病25.1">冠心病25.1</el-checkbox>
                      <el-checkbox label="糖尿病E10-E14"
                        >糖尿病E10-E14</el-checkbox
                      >
                      <el-checkbox label="肺炎J14">肺炎J14</el-checkbox>
                      <el-checkbox label="高血压110">高血压110</el-checkbox>
                      <el-checkbox label="癫痫G40">癫痫G40</el-checkbox>
                      <el-checkbox label="艾滋病B24">艾滋病B24</el-checkbox>
                      <el-checkbox label="慢性肝病衰竭N18-N19"
                        >慢性肝病衰竭N18-N19</el-checkbox
                      >
                      <el-checkbox label="脑出血160-162"
                        >脑出血160-162</el-checkbox
                      >
                      <el-checkbox label="脑梗塞I63">脑梗塞I63</el-checkbox>
                      <el-checkbox label="尿路感染">尿路感染</el-checkbox>
                      <el-checkbox label="帕金森综合症G20-G22"
                        >帕金森综合症G20-G22</el-checkbox
                      >
                      <el-checkbox label="消化道出血K20-K31"
                        >消化道出血K20-K31</el-checkbox
                      >
                      <el-checkbox label="肿瘤C00-D48">肿瘤C00-D48</el-checkbox>
                      <el-checkbox label="截肢(6个月内)"
                        >截肢(6个月内)</el-checkbox
                      >
                      <el-checkbox label="骨折(3个月内)"
                        >骨折(3个月内)</el-checkbox
                      >
                    </el-checkbox-group>
                  </el-form-item>

                  <el-form-item label="用药情况">
                    <el-table
                      :data="healthForm.medications"
                      style="width: 100%"
                    >
                      <el-table-column prop="name" label="药物名称" width="200">
                        <template #default="scope">
                          <el-input
                            v-model="scope.row.name"
                            placeholder="请输入药物名称"
                            :maxlength="20"
                            show-word-limit
                          />
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="method"
                        label="服用方法"
                        width="200"
                      >
                        <template #default="scope">
                          <el-input
                            v-model="scope.row.method"
                            placeholder="请输入服用方法"
                            :maxlength="20"
                            show-word-limit
                          />
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="dosage"
                        label="用药剂量"
                        width="200"
                      >
                        <template #default="scope">
                          <el-input
                            v-model="scope.row.dosage"
                            placeholder="请输入用药剂量"
                            :maxlength="20"
                            show-word-limit
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="100">
                        <template #default="scope">
                          <el-button
                            link
                            type="danger"
                            @click="removeMedication(scope.$index)"
                          >
                            <el-icon><Minus /></el-icon>
                          </el-button>
                          <el-button link type="primary" @click="addMedication">
                            <el-icon><Plus /></el-icon>
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </el-form>
              </div>

              <div class="assessment-section">
                <h4>近30天内风险事件</h4>
                <el-form :model="healthForm" label-width="120px">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="跌倒" required>
                        <el-radio-group v-model="healthForm.fallRisk">
                          <el-radio label="无">无</el-radio>
                          <el-radio label="发生过1次">发生过1次</el-radio>
                          <el-radio label="发生过2次">发生过2次</el-radio>
                          <el-radio label="发生过3次以上"
                            >发生过3次以上</el-radio
                          >
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="走失" required>
                        <el-radio-group v-model="healthForm.lostRisk">
                          <el-radio label="无">无</el-radio>
                          <el-radio label="发生过1次">发生过1次</el-radio>
                          <el-radio label="发生过2次">发生过2次</el-radio>
                          <el-radio label="发生过3次以上"
                            >发生过3次以上</el-radio
                          >
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="噎食" required>
                        <el-radio-group v-model="healthForm.chokingRisk">
                          <el-radio label="无">无</el-radio>
                          <el-radio label="发生过1次">发生过1次</el-radio>
                          <el-radio label="发生过2次">发生过2次</el-radio>
                          <el-radio label="发生过3次以上"
                            >发生过3次以上</el-radio
                          >
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="自杀" required>
                        <el-radio-group v-model="healthForm.suicideRisk">
                          <el-radio label="无">无</el-radio>
                          <el-radio label="发生过1次">发生过1次</el-radio>
                          <el-radio label="发生过2次">发生过2次</el-radio>
                          <el-radio label="发生过3次以上"
                            >发生过3次以上</el-radio
                          >
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-form-item label="昏迷" required>
                    <el-radio-group v-model="healthForm.comaRisk">
                      <el-radio label="无">无</el-radio>
                      <el-radio label="发生过1次">发生过1次</el-radio>
                      <el-radio label="发生过2次">发生过2次</el-radio>
                      <el-radio label="发生过3次以上">发生过3次以上</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>

              <div class="assessment-section">
                <h4>身体健康情况</h4>
                <el-form :model="healthForm" label-width="120px">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="伤口情况" required>
                        <el-radio-group v-model="healthForm.woundCondition">
                          <el-radio label="无">无</el-radio>
                          <el-radio label="擦伤">擦伤</el-radio>
                          <el-radio label="烧伤">烧伤</el-radio>
                          <el-radio label="术后伤口">术后伤口</el-radio>
                          <el-radio label="糖尿病足溃疡">糖尿病足溃疡</el-radio>
                          <el-radio label="血管性溃疡">血管性溃疡</el-radio>
                          <el-radio label="其他伤口">其他伤口</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="特殊医疗服务" required>
                        <el-checkbox-group
                          v-model="healthForm.specialMedicalServices"
                        >
                          <el-checkbox label="无">无</el-checkbox>
                          <el-checkbox label="胃管">胃管</el-checkbox>
                          <el-checkbox label="尿管">尿管</el-checkbox>
                          <el-checkbox label="气管切开">气管切开</el-checkbox>
                          <el-checkbox label="无创呼吸机"
                            >无创呼吸机</el-checkbox
                          >
                        </el-checkbox-group>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-form-item label="自理能力" required>
                    <el-radio-group v-model="healthForm.selfCareAbility">
                      <el-radio label="可自理">可自理</el-radio>
                      <el-radio label="轻度依赖">轻度依赖</el-radio>
                      <el-radio label="中度依赖">中度依赖</el-radio>
                      <el-radio label="重度依赖">重度依赖</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="痴呆前兆">
                    <el-checkbox-group v-model="healthForm.dementiaSigns">
                      <el-checkbox label="行为异常">行为异常</el-checkbox>
                      <el-checkbox label="记忆障碍">记忆障碍</el-checkbox>
                      <el-checkbox label="日常生活能力减退"
                        >日常生活能力减退</el-checkbox
                      >
                      <el-checkbox label="其他">其他</el-checkbox>
                    </el-checkbox-group>
                    <!-- 动态显示其他输入框 -->
                    <el-input
                      v-if="healthForm.dementiaSigns.includes('其他')"
                      v-model="healthForm.otherDementiaSigns"
                      placeholder="请输入其他痴呆前兆"
                      :maxlength="20"
                      show-word-limit
                      style="margin-top: 10px"
                    />
                  </el-form-item>
                </el-form>
              </div>

              <div class="assessment-section">
                <h4>近期体检报告</h4>
                <el-form-item label="体检报告">
                  <el-upload
                    action="#"
                    :auto-upload="false"
                    :on-change="handleMedicalReportUpload"
                    :file-list="medicalReportFiles"
                    :on-preview="(file) => previewFile(file)"
                  >
                    <el-button type="primary">上传文件</el-button>
                    <template #tip>
                      <div class="el-upload__tip">
                        请上传pdf文件，大小在60M以内
                      </div>
                    </template>
                    <template #file="{ file }">
                      <div
                        class="el-upload-list__item-content"
                        @click.stop="previewFile(file)"
                        style="cursor: pointer"
                      >
                        <el-icon><Document /></el-icon>
                        <span class="el-upload-list__item-name">{{
                          file.name
                        }}</span>
                        <el-button
                          type="text"
                          size="small"
                          @click.stop="handleMedicalReportRemove(file)"
                        >
                          删除
                        </el-button>
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </div>
            </div>

            <!-- 2.2 能力评估 -->
            <div
              v-else-if="currentAssessmentTab === 2"
              class="tab-panel-content"
            >
              <div class="ability-assessment">
                <div class="assessment-question">
                  <h4>*1.进食：使用适当的器具将食物送入嘴中并嚼下</h4>
                  <el-radio-group v-model="abilityForm.eating">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*2.洗澡：清洗和擦干身体</h4>
                  <el-radio-group v-model="abilityForm.bathing">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*3.修饰：指洗脸、刷牙、梳头、刮脸、剪指（趾）甲等</h4>
                  <el-radio-group v-model="abilityForm.grooming">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*4.穿衣：包括穿脱衣服、鞋子和系扣等</h4>
                  <el-radio-group v-model="abilityForm.dressing">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*5.如厕：包括如厕动作、清洁和使用卫生纸等</h4>
                  <el-radio-group v-model="abilityForm.toileting">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*6.转移：从床到椅子或轮椅的转移</h4>
                  <el-radio-group v-model="abilityForm.transferring">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*7.行走：在室内或室外行走</h4>
                  <el-radio-group v-model="abilityForm.walking">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*8.沟通：理解和表达信息的能力</h4>
                  <el-radio-group v-model="abilityForm.communication">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*9.认知：记忆力、注意力和判断力</h4>
                  <el-radio-group v-model="abilityForm.cognition">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>

                <div class="assessment-question">
                  <h4>*10.社会交往：与他人互动和参与社交活动</h4>
                  <el-radio-group v-model="abilityForm.socialInteraction">
                    <el-radio label="A">A.独立完成，不需要协助</el-radio>
                    <el-radio label="B">B.在他人语言指导或照看下完成</el-radio>
                    <el-radio label="C"
                      >C.需要他人协助，但以自身完成为主</el-radio
                    >
                    <el-radio label="D">D.主要依靠协助，自身能予配合</el-radio>
                    <el-radio label="E"
                      >E.完全依赖他人协助，且无法给予配合</el-radio
                    >
                  </el-radio-group>
                </div>
              </div>
            </div>

            <!-- 2.3 评估报告 -->
            <div
              v-else-if="currentAssessmentTab === 3"
              class="tab-panel-content"
            >
              <div class="assessment-report">
                <div class="result-section">
                  <h4>能力评估结果</h4>

                  <el-row :gutter="20">
                    <el-col :span="12">
                      <div class="score-card">
                        <h5>各指标分数（分）</h5>
                        <div class="scores">
                          <span
                            >自理能力得分：{{
                              assessmentResults.selfCareScore
                            }}</span
                          >
                          <span
                            >精神状态得分：{{
                              assessmentResults.mentalStateScore
                            }}</span
                          >
                          <span
                            >感知觉与社会参与得分：{{
                              assessmentResults.socialParticipationScore
                            }}</span
                          >
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="score-card">
                        <h5>评估总分（分）</h5>
                        <div class="total-score">
                          {{ assessmentResults.totalScore }}
                        </div>
                      </div>
                    </el-col>
                  </el-row>

                  <div class="level-result">
                    <span
                      >能力初步等级：{{
                        assessmentResults.preliminaryLevel
                      }}</span
                    >
                    <span
                      >护理等级结果：{{ assessmentResults.nursingLevel }}</span
                    >
                  </div>
                </div>

                <div class="change-basis">
                  <h4>*能力等级变更依据</h4>
                  <el-checkbox-group
                    v-model="assessmentResults.levelChangeBasis"
                  >
                    <el-checkbox label="已诊断疾病超过3项"
                      >已诊断疾病超过3项</el-checkbox
                    >
                    <el-checkbox label="风险事件超过3次"
                      >风险事件超过3次</el-checkbox
                    >
                    <el-checkbox label="长期处于昏迷状态"
                      >长期处于昏迷状态</el-checkbox
                    >
                    <el-checkbox label="认知障碍/痴呆"
                      >认知障碍/痴呆</el-checkbox
                    >
                    <el-checkbox label="精神类疾病">精神类疾病</el-checkbox>
                    <el-checkbox label="其他">其他</el-checkbox>
                  </el-checkbox-group>
                  <el-input
                    v-if="assessmentResults.levelChangeBasis.includes('其他')"
                    v-model="assessmentResults.otherBasis"
                    placeholder="请输入其他依据"
                    :maxlength="100"
                    show-word-limit
                    style="margin-top: 10px"
                  />
                </div>

                <div class="final-level">
                  <h4>*能力最终等级</h4>
                  <el-radio-group v-model="assessmentResults.finalLevel">
                    <el-radio label="能力完好">能力完好</el-radio>
                    <el-radio label="轻度失能">轻度失能</el-radio>
                    <el-radio label="中度失能">中度失能</el-radio>
                    <el-radio label="其他">其他</el-radio>
                  </el-radio-group>
                  <el-input
                    v-if="assessmentResults.finalLevel === '其他'"
                    v-model="assessmentResults.otherFinalLevel"
                    placeholder="请输入其他等级"
                    :maxlength="100"
                    show-word-limit
                    style="margin-top: 10px"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 3. 入住审批步骤 -->
        <div v-else-if="currentStep === 3" class="step-panel">
          <div class="approval-panel">
            <div class="approval-header">
              <h3>审批结果</h3>
            </div>

            <!-- 审批前状态 -->
            <div v-if="!approvalState.showResult" class="approval-status">
              <div class="status-icon">
                <el-icon style="color: #e6a23c; font-size: 48px"
                  ><Warning
                /></el-icon>
              </div>
              <div class="status-text">
                <h4>审批中</h4>
                <p v-if="!canApprove">
                  稍等，入住申请单正在审批中，若该申请单长时间未处理，请联系管理员!
                </p>
                <p v-else>
                  请审批此入住申请单
                </p>
              </div>
            </div>

            <!-- 审批后状态 - 显示审批结果和操作记录 -->
            <div v-else class="approval-result-container">
              <!-- 左侧：基本信息和健康状况 -->
              <div class="approval-info-section">
                <div class="info-card">
                  <h4>基本信息</h4>
                  <div class="info-item">
                    <span class="label">老人姓名：</span>
                    <span class="value">{{ basicForm.name }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">老人身份证号：</span>
                    <span class="value">{{ basicForm.idCard }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">性别：</span>
                    <span class="value">{{ basicForm.gender }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">出生日期：</span>
                    <span class="value">{{ basicForm.birthDate }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">详细住址：</span>
                    <span class="value">{{ basicForm.address }}</span>
                  </div>
                </div>

                <div class="info-card">
                  <h4>健康状况</h4>
                  <div class="info-item">
                    <span class="label">疾病和用药情况</span>
                  </div>
                  <div class="disease-list">
                    <el-tag
                      v-for="(disease, index) in healthForm.diseases"
                      :key="index"
                      class="disease-tag"
                    >
                      {{ disease }}
                    </el-tag>
                  </div>
                  <div class="info-item" v-if="healthForm.otherDiseases">
                    <span class="value">{{ healthForm.otherDiseases }}</span>
                  </div>
                </div>
              </div>

              <!-- 右侧：审批结果和操作记录 -->
              <div class="approval-actions-section">
                <div class="info-card">
                  <h4>审批结果</h4>
                  <!-- 管理员可以操作审批 -->
                  <div v-if="canApprove" class="approval-radio-group">
                    <el-radio
                      v-model="approvalState.approvalResult"
                      label="审批通过"
                      >审批通过</el-radio
                    >
                    <el-radio
                      v-model="approvalState.approvalResult"
                      label="审批拒绝"
                      >审批拒绝</el-radio
                    >
                    <el-radio
                      v-model="approvalState.approvalResult"
                      label="驳回"
                      >驳回</el-radio
                    >
                  </div>
                  <!-- 护理员只能查看审批结果 -->
                  <div v-else class="approval-result-display">
                    <div class="result-item">
                      <span class="label">审批结果：</span>
                      <el-tag 
                        :type="approvalState.approvalResult === '审批通过' ? 'success' : 
                               approvalState.approvalResult === '审批拒绝' ? 'danger' : 'warning'"
                      >
                        {{ approvalState.approvalResult || '待审批' }}
                      </el-tag>
                    </div>
                  </div>
                  
                  <div class="approval-comment">
                    <label for="approvalComment">审批意见</label>
                    <el-input
                      v-model="approvalState.approvalComment"
                      type="textarea"
                      rows="3"
                      placeholder="请输入"
                      maxlength="200"
                      show-word-limit
                      :disabled="!canApprove"
                    ></el-input>
                  </div>
                </div>

                <!-- 🔥【修改】审批记录 - 支持点击查看详情 -->
                <div class="info-card">
                  <h4>审批记录</h4>
                  <div class="approval-records-list">
                    <!-- 显示审批记录（可点击查看） -->
                    <div
                      v-for="(record, index) in approvalRecords"
                      :key="index"
                      class="approval-record-item"
                      @click="viewApprovalRecord(record)"
                    >
                      <div class="record-header">
                        <div class="record-step">
                          <el-tag :type="getStepTagType(record.stepId)" size="small">
                            {{ record.stepName }}
                          </el-tag>
                        </div>
                        <div class="record-time">{{ record.approvalTime }}</div>
                      </div>
                      <div class="record-content">
                        <div class="record-approver">
                          {{ record.approver }}（{{ record.approverRole }}）
                        </div>
                        <div class="record-result">
                          <el-tag 
                            :type="record.approvalResult === '审批通过' ? 'success' : 
                                   record.approvalResult === '审批拒绝' ? 'danger' : 'warning'"
                            size="small"
                          >
                            {{ record.approvalResult }}
                          </el-tag>
                        </div>
                      </div>
                      <div class="record-comment" v-if="record.approvalComment">
                        <el-icon><Document /></el-icon>
                        {{ record.approvalComment }}
                      </div>
                      <div class="record-action-hint">
                        <el-icon><View /></el-icon>
                        点击查看详情
                      </div>
                    </div>
                    
                    <!-- 如果没有审批记录 -->
                    <el-empty 
                      v-if="approvalRecords.length === 0" 
                      description="暂无审批记录"
                      :image-size="80"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 4. 入住配置步骤 -->
        <div v-else-if="currentStep === 4" class="step-panel">
          <div class="panel-header">
            <h2>选择入住配置</h2>
          </div>

          <div class="configuration-content">
            <div class="config-section">
              <h4>1 入住设置</h4>
              <el-form :model="configForm" label-width="120px">
                <el-form-item label="入住期限" required>
                  <el-date-picker
                    v-model="configForm.stayPeriod"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="请选择开始日期"
                    end-placeholder="请选择结束日期"
                  />
                </el-form-item>
                <el-form-item label="护理等级" required>
                  <el-select
                    v-model="configForm.nursingLevel"
                    placeholder="请选择护理等级"
                  >
                    <el-option
                      v-for="item in dictData.nursingLevelList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="入住床位" required>
                  <div class="bed-info">
                    <el-button type="primary" @click="showBedSelection"
                      >选择入住床位</el-button
                    >
                    <span v-if="configForm.selectedBed" class="selected-bed">{{
                      configForm.selectedBed
                    }}</span>
                  </div>
                </el-form-item>
              </el-form>
            </div>

            <div class="config-section">
              <h4>2 费用设置</h4>
              <p class="fee-notice">该费用为月账单，每月1号收当月费用</p>
              <el-form :model="configForm" label-width="120px">
                <el-form-item label="费用期限" required>
                  <el-date-picker
                    v-model="configForm.feePeriod"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="请选择开始日期"
                    end-placeholder="请选择结束日期"
                  />
                </el-form-item>
                <el-form-item label="押金（元）">
                  <el-input-number
                    v-model="configForm.deposit"
                    :min="0"
                    :step="100"
                  />
                </el-form-item>
                <el-form-item label="护理费用（元/月）">
                  <el-input-number
                    v-model="configForm.nursingFee"
                    :min="0"
                    :step="100"
                  />
                </el-form-item>
                <el-form-item label="床位费用（元/月）">
                  <el-input-number
                    v-model="configForm.bedFee"
                    :min="0"
                    :step="100"
                  />
                </el-form-item>
                <el-form-item label="其他费用（元/月）">
                  <el-input-number
                    v-model="configForm.otherFee"
                    :min="0"
                    :step="100"
                  />
                </el-form-item>
                <el-form-item label="医保支付（元/月）">
                  <el-input-number
                    v-model="configForm.insurancePayment"
                    :min="0"
                    :step="100"
                  />
                </el-form-item>
                <el-form-item label="政府补贴（元/月）">
                  <el-input-number
                    v-model="configForm.governmentSubsidy"
                    :min="0"
                    :step="100"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="showBillPreview"
                    >账单预览</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>

        <!-- 5. 签约办理步骤 -->
        <div v-else-if="currentStep === 5" class="step-panel">
          <div class="panel-header">
            <h2>完成签约办理</h2>
          </div>

          <div class="contract-content">
            <div class="contract-section">
              <h4>1 签约信息</h4>
              <el-form :model="contractForm" label-width="120px">
                <el-form-item label="合同编号" required>
                  <el-input
                    v-model="contractForm.contractNumber"
                    placeholder="请输入合同编号"
                    :maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item label="合同名称" required>
                  <el-input
                    v-model="contractForm.contractName"
                    placeholder="请输入合同名称"
                    :maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item label="合同开始时间" required>
                  <el-date-picker
                    v-model="contractForm.contractStartTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="选择开始日期"
                  />
                </el-form-item>
                <el-form-item label="合同结束时间" required>
                  <el-date-picker
                    v-model="contractForm.contractEndTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="选择结束日期"
                  />
                </el-form-item>
                <el-form-item label="签约日期" required>
                  <el-date-picker
                    v-model="contractForm.signDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="选择日期"
                  />
                </el-form-item>
                <el-form-item label="丙方姓名">
                  <el-input
                    v-model="contractForm.partyCName"
                    placeholder="请输入丙方姓名"
                    :maxlength="10"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item label="丙方联系方式">
                  <el-input
                    v-model="contractForm.partyCcontact"
                    placeholder="请输入丙方联系方式"
                    :maxlength="11"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item label="合同文件">
                  <!-- 显示已存在的合同文件 -->
                  <div v-if="contractForm.contractFile" class="existing-file">
                    <div class="file-item">
                      <el-icon><Document /></el-icon>
                      <span class="file-name">{{ typeof contractForm.contractFile === 'string' ? extractFileNameFromUrl(contractForm.contractFile, '合同文件.pdf') : (contractForm.contractFile.name || '合同文件') }}</span>
                      <div class="file-actions">
                        <el-button 
                          type="primary" 
                          size="small" 
                          @click="handleContractFilePreview"
                        >
                          <el-icon><ZoomIn /></el-icon>
                          预览
                        </el-button>
                        <el-button 
                          type="danger" 
                          size="small" 
                          @click="handleContractFileRemove"
                        >
                          <el-icon><Delete /></el-icon>
                          删除
                        </el-button>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 上传新文件 -->
                  <el-upload
                    action="#"
                    :auto-upload="false"
                    :on-change="handleContractUpload"
                    :file-list="contractFiles"
                    :on-preview="handleContractPreview"
                    :on-remove="handleContractRemove"
                    accept=".pdf"
                    :show-file-list="false"
                  >
                    <el-button type="primary">
                      <el-icon><Upload /></el-icon>
                      {{ contractForm.contractFile ? '重新上传' : '上传文件' }}
                    </el-button>
                    <template #tip>
                      <div class="el-upload__tip">
                        请上传pdf文件，大小在60M以内
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <!-- 🔥【修改】查看模式下显示"返回审批记录"按钮 -->
        <el-button v-if="isViewMode" @click="router.push('/xtgz/xtgz/record')">返回审批记录</el-button>
        
        <!-- 非查看模式下的按钮 -->
        <template v-if="!isViewMode">
          <el-button v-if="currentStep === 1 && currentApplyTab === 1" @click="handleReturnToList">返回</el-button>
          <el-button v-if="currentStep > 1" @click="previousStep">返回</el-button>
          
          <!-- 🔥【新增】审批模式下，如果当前查看的不是自己负责的步骤，显示跳转按钮 -->
          <el-button 
            v-if="isApprovalMode && currentStep !== getCurrentUserStep()" 
            type="warning" 
            @click="jumpToMyStep"
            style="margin-right: 10px;"
          >
            <el-icon><Right /></el-icon>
            跳转到我的任务（第{{ getCurrentUserStep() }}步）
          </el-button>
          
          <!-- 测试用默认值填充按钮 -->
          <el-button 
            v-if="!isApprovalMode && currentStep === 1" 
            type="success" 
            @click="fillDefaultTestValues"
            style="margin-right: 10px;"
          >
            <el-icon><Setting /></el-icon>
            填充测试数据
          </el-button>
          
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :disabled="currentStep === 3 && !canApprove && !approvalState.showResult"
          >
            {{ getSubmitButtonText() }}
            <!-- 动态生成按钮文本 -->
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </template>
      </div>
    </div>

    <!-- 账单预览对话框 -->
    <el-dialog v-model="billPreviewVisible" title="账单预览" width="600px">
      <div class="bill-preview-content">
        <div class="bill-header">
          <h3>费用清单</h3>
          <div class="bill-info">
            <p>
              <span class="label">老人姓名：</span
              >{{ billPreviewData.residentName }}
            </p>
            <p>
              <span class="label">费用期限：</span
              >{{ billPreviewData.billPeriod }}
            </p>
          </div>
        </div>

        <div class="bill-details">
          <div class="bill-row bill-header-row">
            <div class="bill-col">项目</div>
            <div class="bill-col">金额(元)</div>
          </div>
          <div
            v-for="(item, index) in billPreviewData.details"
            :key="index"
            :class="['bill-row', item.isTotal ? 'bill-total-row' : '']"
          >
            <div class="bill-col">{{ item.name }}</div>
            <div class="bill-col">{{ item.amount.toFixed(2) }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="billPreviewVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 合同预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="合同预览"
      width="900px"
      height="80vh"
    >
      <div class="pdf-preview-container">
        <div v-if="currentContractFile" class="pdf-info">
          <h3>{{ currentContractFile.name }}</h3>
          <p>文件大小: {{ formatFileSize(currentContractFile.size || 0) }}</p>
          <div class="pdf-content" v-if="pdfPreviewUrl">
            <embed
              :src="pdfPreviewUrl"
              type="application/pdf"
              width="100%"
              height="600px"
            />
          </div>
          <div class="pdf-placeholder" v-else>
            <el-empty description="正在加载PDF文件..." />
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 床位选择对话框 -->
    <el-dialog v-model="bedDialogVisible" title="选择入住床位" width="900px">
      <div v-loading="bedData.loading" class="bed-selection">
        <!-- 按楼层分组显示床位 -->
        <div v-for="floor in bedData.floorList" :key="floor.id" class="bed-building">
          <h4>{{ floor.floorNo }}</h4>
          <!-- 按房间分组显示床位 -->
          <div v-for="room in floor.roomList" :key="room.id" class="room-section">
            <h5 class="room-title">{{ room.roomNo }}</h5>
            <div class="bed-list">
              <el-radio-group v-model="tempSelectedBed">
                <div v-for="bed in room.bedList" :key="bed.id" class="bed-item">
                  <el-radio 
                    :label="bed.id" 
                    :disabled="bed.status === '1' || bed.status === 1"
                  >
                    <span class="bed-name">{{ bed.bedNo }}</span>
                    <el-tag 
                      :type="getBedStatusTagType(bed.status)" 
                      size="small" 
                      class="bed-status-tag"
                    >
                      {{ getBedStatusText(bed.status) }}
                    </el-tag>
                  </el-radio>
                </div>
              </el-radio-group>
            </div>
          </div>
          <!-- 如果房间列表为空 -->
          <div v-if="!floor.roomList || floor.roomList.length === 0" class="empty-hint">
            该楼层暂无房间
          </div>
        </div>
        <!-- 如果床位列表为空 -->
        <el-empty 
          v-if="!bedData.floorList || bedData.floorList.length === 0" 
          description="暂无可用床位，请先在房间管理中添加床位"
        />
      </div>
      <template #footer>
        <el-button @click="bedDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBedSelection" :disabled="!tempSelectedBed">确定</el-button>
      </template>
    </el-dialog>

    <!-- 🔥【新增】审批记录查看对话框 -->
    <el-dialog 
      v-model="approvalRecordDialogVisible" 
      title="审批记录详情" 
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="currentViewingRecord" class="approval-record-detail">
        <!-- 审批信息卡片 -->
        <el-card class="record-info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>审批信息</span>
              <el-tag :type="getStepTagType(currentViewingRecord.stepId)">
                {{ currentViewingRecord.stepName }}
              </el-tag>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="审批人">
              {{ currentViewingRecord.approver }}
            </el-descriptions-item>
            <el-descriptions-item label="审批角色">
              {{ currentViewingRecord.approverRole }}
            </el-descriptions-item>
            <el-descriptions-item label="审批时间" :span="2">
              {{ currentViewingRecord.approvalTime }}
            </el-descriptions-item>
            <el-descriptions-item label="审批结果">
              <el-tag 
                :type="currentViewingRecord.approvalResult === '审批通过' ? 'success' : 
                       currentViewingRecord.approvalResult === '审批拒绝' ? 'danger' : 'warning'"
              >
                {{ currentViewingRecord.approvalResult }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="审批意见" :span="2">
              {{ currentViewingRecord.approvalComment || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 表单数据快照（只读模式） -->
        <el-card class="record-data-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>当时的表单数据</span>
              <el-tag type="info" size="small">只读模式</el-tag>
            </div>
          </template>
          <div class="form-snapshot">
            <el-alert
              title="这是该步骤提交时的数据快照，仅供查看"
              type="info"
              :closable="false"
              show-icon
            />
            <!-- TODO: 根据步骤ID显示对应的表单数据 -->
            <div class="snapshot-content">
              <pre>{{ JSON.stringify(currentViewingRecord.formData, null, 2) }}</pre>
            </div>
          </div>
        </el-card>

        <!-- 查看完整表单按钮 -->
        <div class="record-actions">
          <el-button 
            type="primary" 
            @click="viewFullFormFromRecord(currentViewingRecord)"
            icon="View"
          >
            在表单中查看完整数据
          </el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="approvalRecordDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入工具函数
import { useDict } from "@/utils/dict";
// 引入响应式API
import { ref, reactive, computed, onMounted, onUnmounted, toRefs, watch, onBeforeUnmount, nextTick } from "vue";
// 引入路由相关
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
// 引入用户store
import useUserStore from "@/store/modules/user";
// 引入Element Plus组件（按需）
import { ElMessage, ElSelect, ElOption, ElImage, ElEmpty, ElMessageBox } from "element-plus";
// 引入家属信息API
import { listMember } from "@/api/system/member";
// 引入合同API
import { listContract } from "@/api/system/contract";
// 引入入住管理API
import { completeApplication, startWorkflow, handleTask, getManagement, saveAssessmentDraft, getAssessmentDraft, configureCheckIn, signContract } from "@/api/system/management";
// 🔥 引入护理等级和床位API
import { listNursingLevel, listBed, listFloorAllRelations } from "@/api/system/roomManage";
// 引入axios用于文件上传
import axios from "axios";
// 引入token获取函数
import { getToken } from "@/utils/auth";
import {
  Plus,
  Minus,
  Warning,
  Delete,
  View,
  Document,
  ZoomIn,
  Setting,
  Right,
} from "@element-plus/icons-vue";

// 全局错误处理 - 只处理脚本错误，忽略资源加载错误
window.addEventListener('error', (event) => {
  // ✅ 忽略资源加载错误（图片、样式、脚本等）
  if (event.target !== window) {
    return;
  }
  
  // 只记录真正的JavaScript错误
  if (event.error) {
    console.error('🔴 全局JavaScript错误:', event.error);
    if (event.error.message && event.error.message.includes('checkInForm')) {
      ElMessage.error('页面加载出现错误，请刷新页面重试');
    }
  }
}, true); // 使用捕获阶段可以更好地区分错误类型

window.addEventListener('unhandledrejection', (event) => {
  console.error('🔴 未处理的Promise拒绝:', event.reason);
  if (event.reason && event.reason.message && event.reason.message.includes('checkInForm')) {
    ElMessage.error('页面操作失败，请重试');
  }
});

// 路由实例
const router = useRouter();
const route = useRoute();

// 用户store实例
const userStore = useUserStore();

// ==================== 状态管理 ====================
// 当前步骤和标签页状态管理
const currentStep = ref(1); // 当前流程步骤(1-5)
const currentApplyTab = ref(1); // 申请入住标签页(1-3)
const currentAssessmentTab = ref(1); // 入住评估标签页(1-3)
const bedDialogVisible = ref(false); // 床位选择弹窗显示状态
const isRestoringDraft = ref(false); // 🔥【关键标志】标记是否正在恢复草稿数据，防止watch触发重新计算
const lastAutoSaveTime = ref(null); // 🔥 记录最后一次自动保存的时间
const isSaving = ref(false); // 🔥 标记是否正在保存中

// ==================== 用户权限管理 ====================
// 用户角色检查 - 根据流程图定义的角色
const isElderlyCareConsultant = computed(() => {
  return userStore.roles.includes('rzyanglaoguwen'); // 养老顾问
});

const isNursingTeamLeader = computed(() => {
  return userStore.roles.includes('rzhuliyuanzuzhang'); // 护理组部长
});

const isVicePresident = computed(() => {
  return userStore.roles.includes('rzfuyuanzhang'); // 副院长
});

const isLegalStaff = computed(() => {
  return userStore.roles.includes('rzfawubuyuangong'); // 法务部员工
});

// 是否为审批模式（从待办任务跳转过来）
const isApprovalMode = computed(() => {
  return route.query.mode === 'approval';
});

// 🔥【新增】是否为查看模式（从审批记录跳转过来）
const isViewMode = computed(() => {
  return route.query.mode === 'view';
});

// 🔥【新增】查看模式下用户可访问的最大步骤（从审批记录获取）
const maxViewableStep = ref(5);

// 当前用户是否可以审批（根据角色和当前步骤）
const canApprove = computed(() => {
  return isApprovalMode.value && (
    (currentStep.value === 1 && isElderlyCareConsultant.value) || // 申请入住
    (currentStep.value === 2 && isNursingTeamLeader.value) ||     // 入住评估
    (currentStep.value === 3 && isVicePresident.value) ||       // 入住审批
    (currentStep.value === 4 && isElderlyCareConsultant.value) || // 入住配置
    (currentStep.value === 5 && isLegalStaff.value)              // 签约办理
  );
});

// 🔥【新增】表单是否为只读模式
// 查看模式下，所有字段都只读
// 审批模式下，只有当前步骤且有权限的用户才能编辑
const isFormReadOnly = computed(() => {
  // 查看模式：全部只读
  if (isViewMode.value) {
    return true;
  }
  
  // 审批模式：检查是否有权限编辑当前步骤
  if (isApprovalMode.value) {
    return !canEditCurrentStep(currentStep.value);
  }
  
  // 普通模式：可编辑
  return false;
});

// 未保存数据提示
const hasUnsavedChanges = ref(false);

// 工作流相关状态
const workflowStarted = ref(false); // 工作流是否已启动
const currentTaskId = ref(''); // 当前任务ID
const processInstanceId = ref(''); // 流程实例ID
const workflowStatus = ref(''); // 工作流状态

// 表单引用
const basicFormRef = ref(null);
const approvalFormRef = ref(null);
const configFormRef = ref(null);
const contractFormRef = ref(null);

// ==================== 步骤和标签页配置 ====================
// 主流程步骤数据
const steps = ref([
  { id: 1, label: "申请入住" },
  { id: 2, label: "入住评估" },
  { id: 3, label: "入住审批" },
  { id: 4, label: "入住配置" },
  { id: 5, label: "签约办理" },
]);

// 申请入住标签页数据
const applyTabs = ref([
  { id: 1, label: "基本信息" },
  { id: 2, label: "家属信息" },
  { id: 3, label: "资料上传" },
]);

// 评估标签页数据
const assessmentTabs = ref([
  { id: 1, label: "健康评估" },
  { id: 2, label: "能力评估" },
  { id: 3, label: "评估报告" },
]);

// ==================== 字典数据管理 ====================
// 字典数据存储（key对应字典类型编码，value是字典选项列表）
const dictData = reactive({
  nationList: [],
  politicalList: [],
  religionList: [],
  maritalList: [],
  educationList: [],
  incomeList: [],
  hobbyList: [],
  medicalList: [],
  familyRelationshipList: [], // 家属关系列表
  nursingLevelList: [], // 🔥 从数据库获取的护理等级列表
});

// 获取字典数据
let dictResult = null;
try {
  dictResult = useDict(
    "lekang_ethnicgroup",
    "lekang_politicalstatus",
    "lekang_religiousbelief",
    "maritalstatus_zd",
    "lekazng_educationallevel",
    "lekang_sourceofincome",
    "hobby",
    "lekang_healthcaresecurity"
  );
} catch (error) {
  console.error("字典数据初始化失败:", error);
  dictResult = null;
}

// 初始化字典数据
if (dictResult) {
  dictData.nationList = dictResult.lekang_ethnicgroup || [];
  dictData.politicalList = dictResult.lekang_politicalstatus || [];
  dictData.religionList = dictResult.lekang_religiousbelief || [];
  dictData.maritalList = dictResult.maritalstatus_zd || [];
  dictData.educationList = dictResult.lekazng_educationallevel || [];
  dictData.incomeList = dictResult.lekang_sourceofincome || [];
  dictData.hobbyList = dictResult.hobby || [];
  dictData.medicalList = dictResult.lekang_healthcaresecurity || [];
  dictData.familyRelationshipList = dictResult.lekang_relationship || [];
  // 护理等级不再从字典获取，改为从数据库获取
}

// ==================== 表单数据定义 ====================
// 基本信息表单数据
const basicForm = reactive({
  name: "",
  idCard: "",
  gender: "",
  birthDate: "",
  age: "",
  contact: "",
  address: "",
  ethnicity: "",
  politicalStatus: "",
  religion: "",
  maritalStatus: "",
  education: "",
  incomeSource: "",
  hobbies: "",
  medicalInsurance: "",
  medicalCardNo: "",
});

/**
 * 获取字典数据
 */
const getDictList = async () => {
  try {
    // 如果字典数据已经初始化，直接返回
    if (dictResult) {
      return { success: true };
    }
    
    // 如果字典数据未初始化，尝试重新获取
    const result = useDict(
      "lekang_ethnicgroup",
      "lekang_politicalstatus", 
      "lekang_religiousbelief",
      "maritalstatus_zd",
      "lekazng_educationallevel",
      "lekang_sourceofincome",
      "hobby",
      "lekang_healthcaresecurity"
    );
    
    // 更新字典数据
    if (result) {
      dictData.nationList = result.lekang_ethnicgroup || [];
      dictData.politicalList = result.lekang_politicalstatus || [];
      dictData.religionList = result.lekang_religiousbelief || [];
      dictData.maritalList = result.maritalstatus_zd || [];
      dictData.educationList = result.lekazng_educationallevel || [];
      dictData.incomeList = result.lekang_sourceofincome || [];
      dictData.hobbyList = result.hobby || [];
      dictData.medicalList = result.lekang_healthcaresecurity || [];
      dictData.familyRelationshipList = result.lekang_relationship || [];
    }
    
    return { success: true };
  } catch (error) {
    console.error("获取字典数据失败:", error);
    return { success: false, error };
  }
};

/**
 * 根据label获取字典值（value）
 * @param {Array} dictList - 字典列表
 * @param {String} label - 显示标签
 * @returns {String} 字典值
 */
const getDictValue = (dictList, label) => {
  if (!label || !Array.isArray(dictList)) return '';
  const item = dictList.find(d => d.label === label || d.value === label);
  return item ? item.value : ''; // 🔥 修复：如果找不到，返回空字符串而不是原值
};

/**
 * 字典value转label
 * @param {Array} dictList - 字典列表
 * @param {String|Number} value - 字典值
 * @returns {String} 字典标签
 */
const getDictLabel = (dictList, value) => {
  // 处理值为0的情况，0是有效的字典值
  if (value === null || value === undefined || value === "") return "";
  if (!dictList || dictList.length === 0) {
    return value.toString();
  }
  const item = dictList.find((item) => item.value === value.toString());
  return item ? item.label : value.toString();
};

// ==================== 表单验证规则 ====================
// 老人基本信息验证规则
const rules = reactive({
  name: [
    { required: true, message: "请输入老人姓名", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5]{2,10}$/,
      message: "请输入2-10个中文字符",
      trigger: "blur",
    },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /^\d{17}[\dXx]$/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  contact: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  ethnicity: [{ required: true, message: "请选择民族", trigger: "change" }],
  address: [{ required: true, message: "请输入家庭住址", trigger: "blur" }],
});

// 家属信息表单数据
const familyForm = reactive({
  members: [{ name: "", contact: "", relationship: "" }],
});

// 文件上传相关
const photoFiles = ref([]);
const idCardFrontFiles = ref([]);
const idCardBackFiles = ref([]);

/**
 * 处理照片上传
 * @param {Object} file - 上传的文件
 * @returns {Boolean} 验证结果
 */
const handlePhotoChange = (file) => {
  photoFiles.value = [file];
  return checkUpload([file], "一寸照片");
};

/**
 * 文件上传验证函数 - 只检查文件是否存在
 * @param {Array} files - 文件数组
 * @param {String} name - 文件名称
 * @returns {Boolean} 验证结果
 */
const checkUpload = (files, name) => {
  if (!files || files.length === 0) {
    throw new Error(`请上传${name}`);
  }
  return true;
};
// ==================== 评估表单数据 ====================
// 健康评估表单数据
const healthForm = reactive({
  diseases: [],
  medications: [{ name: "", method: "", dosage: "" }], // 初始化一条空的用药记录，方便用户填写
  fallRisk: "",
  lostRisk: "",
  chokingRisk: "",
  suicideRisk: "",
  comaRisk: "",
  woundCondition: "",
  specialMedicalServices: [],
  selfCareAbility: "",
  dementiaSigns: [],
  otherDementiaSigns: "",
});

// 能力评估表单数据
const abilityForm = reactive({
  eating: "",
  bathing: "",
  grooming: "",
  dressing: "",
  toileting: "",
  transferring: "",
  walking: "",
  communication: "",
  cognition: "",
  socialInteraction: "",
});

// 评估结果数据
const assessmentResults = reactive({
  selfCareScore: 0,
  mentalStateScore: 0,
  socialParticipationScore: 0,
  totalScore: 0,
  preliminaryLevel: "",
  nursingLevel: "",
  levelChangeBasis: [],
  otherBasis: "",
  finalLevel: "",
  otherFinalLevel: "",
});

// 审批相关状态
const approvalState = reactive({
  showResult: false, // 是否显示审批结果
  approvalResult: "", // 审批结果
  approvalComment: "", // 审批意见
});

// 操作记录
const operationRecords = ref([]);

// 🔥【新增】审批记录数据结构
const approvalRecords = ref([
  // 审批记录示例结构：
  // {
  //   id: 1,
  //   stepId: 1,  // 步骤ID (1-5)
  //   stepName: '申请入住',
  //   approver: '张三',  // 审批人
  //   approverRole: '养老顾问',  // 审批人角色
  //   approvalResult: '审批通过',  // 审批结果
  //   approvalComment: '资料完整，可以进入下一步',  // 审批意见
  //   approvalTime: '2024-10-20 14:30:00',  // 审批时间
  //   formData: {}  // 该步骤的表单数据快照
  // }
]);

// 审批记录弹窗
const approvalRecordDialogVisible = ref(false);
const currentViewingRecord = ref(null);  // 当前正在查看的审批记录

// ==================== 评估计算逻辑 ====================
/**
 * 计算评估分数的函数
 */
const calculateScore = () => {
  let score = 0;
  const questions = Object.values(abilityForm);

  // 答案A为正确（10分），其他选项得分依次降低
  questions.forEach((answer) => {
    if (answer === "A") score += 10;
    else if (answer === "B") score += 8;
    else if (answer === "C") score += 6;
    else if (answer === "D") score += 4;
    else if (answer === "E") score += 2;
  });

  assessmentResults.selfCareScore = Math.round(score * 0.4); // 40%权重
  assessmentResults.mentalStateScore = Math.round(score * 0.3); // 30%权重
  assessmentResults.socialParticipationScore = Math.round(score * 0.3); // 30%权重
  assessmentResults.totalScore = score;

  // 根据总分自动计算能力等级和护理等级
  if (score >= 90) {
    assessmentResults.preliminaryLevel = "能力完好";
    assessmentResults.finalLevel = "能力完好";
    assessmentResults.nursingLevel = "自理";
  } else if (score >= 70) {
    assessmentResults.preliminaryLevel = "轻度失能";
    assessmentResults.finalLevel = "轻度失能";
    assessmentResults.nursingLevel = "三级护理";
  } else if (score >= 40) {
    assessmentResults.preliminaryLevel = "中度失能";
    assessmentResults.finalLevel = "中度失能";
    assessmentResults.nursingLevel = "二级护理";
  } else {
    assessmentResults.preliminaryLevel = "重度失能";
    assessmentResults.finalLevel = "重度失能";
    assessmentResults.nursingLevel = "一级护理";
  }
};

// 监听能力评估表单变化，实现实时计算分数
// 🔥【关键修复】在恢复草稿数据时不触发计算，避免覆盖已保存的评估分数
watch(
  abilityForm,
  () => {
    if (!isRestoringDraft.value) {
      calculateScore();
    }
  },
  { deep: true }
);

// ==================== 评估缺省数据生成 ====================
/**
 * 生成用于展示的默认评估数据，避免查看时为空白
 * ⚠️ 注意：此函数仅用于查看模式，不应在新建/编辑模式下调用
 */
const populateDefaultAssessmentIfEmpty = () => {
  // 🔥 关键修复：仅在查看模式下填充默认值，编辑模式下不填充
  // 使用 isViewMode.value（computed 属性）判断
  
  // healthForm 缺省（仅查看模式）
  if (isViewMode.value) {
    if (!healthForm.diseases || healthForm.diseases.length === 0) {
      healthForm.diseases = ["高血压"]; // 常见慢病占位
    }
    if (!healthForm.medications || healthForm.medications.length === 0) {
      healthForm.medications = [
        { name: "降压药", method: "口服", dosage: "1片/日" },
      ];
    }
    // 体检报告缺省
    if (!medicalReportFiles.value || medicalReportFiles.value.length === 0) {
      medicalReportFiles.value = [
        {
          uid: "default-medical-report",
          name: "体检报告示例.pdf",
          url: "/profile/template/medical-report-sample.pdf",
        },
      ];
    }
    // 使用表单中定义的选项值（"无"、"发生过1次"等）
    if (!healthForm.fallRisk) healthForm.fallRisk = "无";
    if (!healthForm.lostRisk) healthForm.lostRisk = "无";
    if (!healthForm.chokingRisk) healthForm.chokingRisk = "无";
    if (!healthForm.suicideRisk) healthForm.suicideRisk = "无";
    if (!healthForm.comaRisk) healthForm.comaRisk = "无";
    if (!healthForm.woundCondition) healthForm.woundCondition = "无";
    if (!healthForm.selfCareAbility) healthForm.selfCareAbility = "基本自理";
    
    // abilityForm 缺省（用 B 等选项占位，便于评分）
    const abilityDefault = {
      eating: "B",
      bathing: "B",
      grooming: "B",
      dressing: "B",
      toileting: "B",
      transferring: "B",
      walking: "B",
      communication: "B",
      cognition: "B",
      socialInteraction: "B",
    };
    
    // 🔥【关键修复】只有在真正填充了默认值时才重新计算分数
    let hasFilledDefaults = false;
    Object.keys(abilityDefault).forEach((k) => {
      if (!abilityForm[k]) {
        abilityForm[k] = abilityDefault[k];
        hasFilledDefaults = true;
      }
    });

    // 🔥【关键修复】只在填充了默认值时才重新计算，避免覆盖已保存的评估分数
    if (hasFilledDefaults) {
      calculateScore();
    }
  }
};

// ==================== 必要的字段初始化 ====================
/**
 * 初始化必要的数组和字符串字段，防止null/undefined错误
 * 这不是填充默认值，而是确保字段是正确的数据类型
 */
const initializeRequiredFields = () => {
  // 确保数组字段不为 null
  if (!healthForm.specialMedicalServices) {
    healthForm.specialMedicalServices = [];
  }
  if (!healthForm.dementiaSigns) {
    healthForm.dementiaSigns = [];
  }
  if (!healthForm.otherDementiaSigns) healthForm.otherDementiaSigns = "";
  if (!assessmentResults.levelChangeBasis) assessmentResults.levelChangeBasis = [];
  if (!assessmentResults.otherBasis) assessmentResults.otherBasis = "";
  if (!assessmentResults.otherFinalLevel) assessmentResults.otherFinalLevel = "";
};

// ==================== 其它板块查看缺省数据生成 ====================
/**
 * 查看模式下为合同、家属、配置等板块补齐缺省展示值（仅在为空时填充，不覆盖已有数据）
 */
const populateViewDefaultsIfEmpty = () => {
  // 合同信息缺省
  if (!contractForm.contractName) contractForm.contractName = "入住服务合同";
  if (!contractForm.partyCName && basicForm.name) contractForm.partyCName = basicForm.name;
  if (!contractForm.partyCcontact && basicForm.contact) contractForm.partyCcontact = basicForm.contact;
  // 合同起止日期：优先用费用周期，其次入住期限
  const feeStart = Array.isArray(configForm.feePeriod) && configForm.feePeriod[0];
  const feeEnd = Array.isArray(configForm.feePeriod) && configForm.feePeriod[1];
  const stayStart = Array.isArray(configForm.stayPeriod) && configForm.stayPeriod[0];
  const stayEnd = Array.isArray(configForm.stayPeriod) && configForm.stayPeriod[1];
  if (!contractForm.contractStartTime) contractForm.contractStartTime = normalizeToYMD(feeStart || stayStart || contractForm.contractStartTime);
  if (!contractForm.contractEndTime) contractForm.contractEndTime = normalizeToYMD(feeEnd || stayEnd || contractForm.contractEndTime);
  if (!contractForm.signDate && contractForm.contractStartTime) contractForm.signDate = contractForm.contractStartTime;

  // 家属信息缺省：至少一条
  const members = familyForm.members || [];
  const hasAnyFilled = members.some((m) => (m && (m.name || m.contact || m.relationship)));
  if (!members.length || !hasAnyFilled) {
    familyForm.members = [{
      name: "",
      contact: basicForm.contact || "",
      relationship: "子女",
    }];
  }

  // 入住配置缺省
  if (!configForm.nursingLevel) {
    configForm.nursingLevel = assessmentResults.nursingLevel || "三级护理";
  }
  if (!Array.isArray(configForm.feePeriod) || configForm.feePeriod.length !== 2 || !configForm.feePeriod[0] || !configForm.feePeriod[1]) {
    if (contractForm.contractStartTime && contractForm.contractEndTime) {
      configForm.feePeriod = [contractForm.contractStartTime, contractForm.contractEndTime];
    } else if (stayStart && stayEnd) {
      configForm.feePeriod = [stayStart, stayEnd];
    }
  }
  if (!configForm.selectedBed) configForm.selectedBed = "未分配";
};

// ==================== 通用日期规范化 ====================
/**
 * 将多种日期输入规范化为 YYYY-MM-DD 字符串
 */
const normalizeToYMD = (input) => {
  if (!input && input !== 0) return "";
  // Date 对象
  if (input instanceof Date && !isNaN(input)) {
    const y = input.getFullYear();
    const m = String(input.getMonth() + 1).padStart(2, "0");
    const d = String(input.getDate()).padStart(2, "0");
    return `${y}-${m}-${d}`;
  }
  // 数字时间戳
  if (typeof input === "number") {
    const date = new Date(input);
    if (!isNaN(date)) return normalizeToYMD(date);
  }
  // 字符串：截取日期部分并替换斜杠
  if (typeof input === "string") {
    const trimmed = (input ?? "").toString().trim();
    if (!trimmed) return "";
    const datePart = trimmed.split("T")[0].split(" ")[0];
    const normalized = datePart.replaceAll("/", "-");
    // 若为 yyyy-mm-dd 或 yyyy-m-d
    const match = normalized.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
    if (match) {
      const y = match[1];
      const m = match[2].padStart(2, "0");
      const d = match[3].padStart(2, "0");
      return `${y}-${m}-${d}`;
    }
    // 兜底：尝试 new Date
    const tryDate = new Date(trimmed);
    if (!isNaN(tryDate)) return normalizeToYMD(tryDate);
  }
  return "";
};

// ==================== 配置和签约表单数据 ====================
// 入住配置表单数据
const configForm = reactive({
  stayPeriod: [],
  nursingLevel: "", // 🔥 护理等级ID（从数据库获取的ID）
  feePeriod: [],
  deposit: 0,
  nursingFee: 0, // 🔥 护理费用（从护理等级自动获取）
  bedFee: 0,
  otherFee: 0,
  insurancePayment: 0,
  governmentSubsidy: 0,
  selectedBed: "",
  bedId: null, // 🔥 床位ID
  floorId: null, // 🔥 楼层ID
  roomId: null, // 🔥 房间ID
  bedNo: "", // 🔥 床位号
  planId: null, // 🔥 护理计划ID（从护理等级自动获取）
  checkInStartTime: "", // 🔥 入住开始时间
  checkInEndTime: "", // 🔥 入住结束时间
});

// 签约信息表单数据
const contractForm = reactive({
  contractNumber: "",
  contractName: "",
  contractStartTime: "",
  contractEndTime: "",
  signDate: "",
  partyCName: "",
  partyCcontact: "",
  contractFile: null, // 合同文件
});

// 文件上传列表
const medicalReportFiles = ref([]); // 体检报告
const contractFiles = ref([]); // 合同文件

// 🔥 床位数据结构（三级联动：楼层-房间-床位）
const bedData = reactive({
  floorList: [], // 楼层列表
  flatBedList: [], // 扁平化的床位列表（方便查询）
  loading: false,
});

// ==================== 预览和账单管理 ====================
// 合同预览相关
const previewDialogVisible = ref(false);
const currentContractFile = ref(null);
const pdfPreviewUrl = ref("");
const billPreviewVisible = ref(false); // 账单预览弹窗显示状态

// 账单预览数据
const billPreviewData = reactive({
  residentName: "",
  billPeriod: "",
  totalAmount: 0,
  details: [],
});

// 合同上传处理
const handleContractUpload = (file) => {
  // 自动替换旧文件
  contractFiles.value = [file];
  // 同时保存到合同表单中
  contractForm.contractFile = file;
  ElMessage.success("合同文件已上传");
};

// 合同预览处理
const handleContractPreview = (file) => {
  currentContractFile.value = file;

  // 清除之前的URL（如果有）
  if (pdfPreviewUrl.value) {
    URL.revokeObjectURL(pdfPreviewUrl.value);
    pdfPreviewUrl.value = "";
  }

  // 创建新的Blob URL用于PDF预览
  if (file.raw) {
    pdfPreviewUrl.value = URL.createObjectURL(file.raw);
  }

  previewDialogVisible.value = true;
  ElMessage.success(`正在预览文件: ${file.name}`);
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + " B";
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + " KB";
  } else {
    return (size / (1024 * 1024)).toFixed(2) + " MB";
  }
};

// ==================== 🔥 从数据库加载护理等级列表 ====================
const loadNursingLevels = async () => {
  try {
    const response = await listNursingLevel({ pageSize: 1000, status: 1 }); // 只获取启用状态的护理等级
    if (response && response.rows) {
      dictData.nursingLevelList = response.rows.map(item => ({
        value: item.id,
        label: item.levelName,
        nursingFee: item.nursingFee, // 保存护理费用
        planId: item.planId, // 保存护理计划ID
      }));
      console.log('✅ 护理等级加载成功:', dictData.nursingLevelList);
    }
  } catch (error) {
    console.error('❌ 加载护理等级失败:', error);
    ElMessage.error('加载护理等级失败');
  }
};

// ==================== 🔥 从数据库加载床位列表（三级联动） ====================
const loadBedList = async () => {
  try {
    bedData.loading = true;
    // 获取所有楼层及其关联的房间和床位
    const response = await listFloorAllRelations();
    if (response && response.data) {
      bedData.floorList = response.data;
      // 扁平化床位列表，方便查询
      const beds = [];
      response.data.forEach(floor => {
        if (floor.roomList && floor.roomList.length > 0) {
          floor.roomList.forEach(room => {
            if (room.bedList && room.bedList.length > 0) {
              room.bedList.forEach(bed => {
                beds.push({
                  bedId: bed.id,
                  bedNo: bed.bedNo,
                  roomId: room.id,
                  roomName: room.roomName,
                  floorId: floor.id,
                  floorName: floor.floorName,
                  status: bed.status,
                  displayName: `${floor.floorName}-${room.roomName}-${bed.bedNo}号床`
                });
              });
            }
          });
        }
      });
      bedData.flatBedList = beds;
      console.log('✅ 床位列表加载成功:', beds.length, '个床位');
    }
  } catch (error) {
    console.error('❌ 加载床位列表失败:', error);
    ElMessage.error('加载床位列表失败');
  } finally {
    bedData.loading = false;
  }
};

// ==================== 🔥 监听护理等级变化，自动更新护理费用 ====================
watch(
  () => configForm.nursingLevel,
  (newLevelId) => {
    if (newLevelId && dictData.nursingLevelList.length > 0) {
      const selectedLevel = dictData.nursingLevelList.find(item => item.value === newLevelId);
      if (selectedLevel) {
        configForm.nursingFee = selectedLevel.nursingFee || 0;
        configForm.planId = selectedLevel.planId;
        console.log('💰 护理等级变化，自动更新护理费用:', selectedLevel.nursingFee);
      }
    }
  }
);

// ==================== 🔥 床位状态相关辅助函数 ====================
/**
 * 获取床位状态文本
 * @param {String|Number} status - 床位状态（0=空闲, 1=已入住, 2=请假中）
 * @returns {String} 状态文本
 */
const getBedStatusText = (status) => {
  const statusMap = {
    '0': '空闲',
    0: '空闲',
    '1': '已入住',
    1: '已入住',
    '2': '请假中',
    2: '请假中',
  };
  return statusMap[status] || '未知';
};

/**
 * 获取床位状态Tag类型
 * @param {String|Number} status - 床位状态
 * @returns {String} Tag类型
 */
const getBedStatusTagType = (status) => {
  const typeMap = {
    '0': 'success',
    0: 'success',
    '1': 'danger',
    1: 'danger',
    '2': 'warning',
    2: 'warning',
  };
  return typeMap[status] || 'info';
};

// ==================== 🔥 床位选择相关 ====================
const tempSelectedBed = ref(null);

/**
 * 显示床位选择对话框
 */
const showBedSelection = async () => {
  // 每次打开对话框时重新加载床位列表，确保数据最新
  await loadBedList();
  tempSelectedBed.value = configForm.bedId || null;
  bedDialogVisible.value = true;
};

/**
 * 确认床位选择
 */
const confirmBedSelection = () => {
  if (tempSelectedBed.value) {
    // 从床位列表中找到选中的床位
    const selectedBed = bedData.flatBedList.find(bed => bed.bedId === tempSelectedBed.value);
    if (selectedBed) {
      configForm.bedId = selectedBed.bedId;
      configForm.floorId = selectedBed.floorId;
      configForm.roomId = selectedBed.roomId;
      configForm.bedNo = selectedBed.bedNo;
      configForm.selectedBed = selectedBed.displayName;
      console.log('✅ 床位选择成功:', selectedBed.displayName);
    }
    bedDialogVisible.value = false;
  }
};

// 切换步骤
/**
 * 步骤切换函数 - 包含权限控制
 * @param {number} stepId - 要切换到的步骤ID
 */
const switchStep = (stepId) => {
  // 🔥【新增】如果步骤被禁用，直接返回，不显示提示
  if (isStepDisabled(stepId)) {
    return;
  }
  
  // 🔥【修改】查看模式下，只能查看用户处理的步骤及之前的步骤
  if (isViewMode.value) {
    // 查看模式下，只能查看小于等于maxViewableStep的步骤
    if (stepId <= maxViewableStep.value) {
      currentStep.value = stepId;
      // 重置标签页状态
      if (stepId === 1) currentApplyTab.value = 1;
      if (stepId === 2) currentAssessmentTab.value = 1;
    } else {
      ElMessage.warning(`您只能查看到第${maxViewableStep.value}步，无法查看之后的步骤`);
    }
    return;
  }
  
  // 🔥【修改】审批模式下，可以查看所有历史步骤（只读），但只能编辑当前处理步骤
  if (isApprovalMode.value) {
    const currentUserStep = getCurrentUserStep();
    // 允许查看当前步骤及之前的所有步骤
    if (stepId <= currentUserStep) {
      currentStep.value = stepId;
      // 重置标签页状态
      if (stepId === 1) currentApplyTab.value = 1;
      if (stepId === 2) currentAssessmentTab.value = 1;
    } else {
      ElMessage.warning(`您只能查看到第${currentUserStep}步，无法查看未来步骤`);
    }
    return;
  }
  
  // 普通模式下，只能跳转到已完成或当前步骤
  if (stepId <= currentStep.value) {
    currentStep.value = stepId;
    // 重置标签页状态
    if (stepId === 1) currentApplyTab.value = 1;
    if (stepId === 2) currentAssessmentTab.value = 1;
  }
};

// 处理文件超出限制函数已移除，因为我们在handleContractUpload中自动替换文件

// 合同删除处理
const handleContractRemove = (file) => {
  contractFiles.value = [];
  ElMessage.success("合同文件已删除");
};

// 处理已存在合同文件的预览
const handleContractFilePreview = () => {
  if (contractForm.contractFile) {
    // 合同文件可能是 URL 字符串或包含 raw/url 的文件对象
    currentContractFile.value = typeof contractForm.contractFile === 'string'
      ? { name: extractFileNameFromUrl(contractForm.contractFile, '合同文件.pdf'), size: 0 }
      : contractForm.contractFile;
    
    // 清除之前的URL（如果有）
    if (pdfPreviewUrl.value) {
      URL.revokeObjectURL(pdfPreviewUrl.value);
      pdfPreviewUrl.value = "";
    }
    
    // 如果是文件对象，创建预览URL
    if (contractForm.contractFile && typeof contractForm.contractFile === 'object' && contractForm.contractFile.raw) {
      pdfPreviewUrl.value = URL.createObjectURL(contractForm.contractFile.raw);
    } else if (contractForm.contractFile && typeof contractForm.contractFile === 'object' && contractForm.contractFile.url) {
      pdfPreviewUrl.value = contractForm.contractFile.url;
    } else if (typeof contractForm.contractFile === 'string') {
      pdfPreviewUrl.value = contractForm.contractFile;
    }
    
    previewDialogVisible.value = true;
  }
};

// 处理已存在合同文件的删除
const handleContractFileRemove = () => {
  contractForm.contractFile = null;
  ElMessage.success("合同文件已删除");
};

// 显示账单预览
const showBillPreview = () => {
  // 计算账单数据
  const nursingFee = configForm.nursingFee || 0;
  const bedFee = configForm.bedFee || 0;
  const otherFee = configForm.otherFee || 0;
  const insurancePayment = configForm.insurancePayment || 0;
  const governmentSubsidy = configForm.governmentSubsidy || 0;

  // 计算总费用
  const totalFee = nursingFee + bedFee + otherFee;
  const actualPayment = totalFee - insurancePayment - governmentSubsidy;

  // 填充预览数据
  billPreviewData.residentName = basicForm.name || "老人姓名";
  billPreviewData.billPeriod = configForm.feePeriod
    ? `${configForm.feePeriod[0]} 至 ${configForm.feePeriod[1]}`
    : "未设置";
  billPreviewData.totalAmount = actualPayment;
  billPreviewData.details = [
    { name: "护理费用", amount: nursingFee },
    { name: "床位费用", amount: bedFee },
    { name: "其他费用", amount: otherFee },
    { name: "医保支付", amount: -insurancePayment },
    { name: "政府补贴", amount: -governmentSubsidy },
    { name: "实付金额", amount: actualPayment, isTotal: true },
  ];

  billPreviewVisible.value = true;
};

// 切换申请入住标签页
const switchApplyTab = async (tabId) => {
  // 只有在同一步骤内切换标签页且从较低标签页切换到较高标签页时才需要验证
  // 例如从标签1切换到标签2或3，从标签2切换到标签3
  if (tabId > currentApplyTab.value) {
    try {
      // 验证当前标签页的数据
      await validateCurrentTabForm(currentApplyTab.value);
      // 验证通过，切换标签页
      currentApplyTab.value = tabId;
    } catch (error) {
      console.error("标签页切换验证失败:", error);
      ElMessage.error(error.message || "请完成当前标签页的所有必填内容");
      // 验证失败，不切换标签页
    }
  } else {
    // 从较高标签页切换到较低标签页时，直接切换（不需要验证）
    currentApplyTab.value = tabId;
  }
};

// 切换评估标签页
// 🔥 自动保存评估数据的函数
const autoSaveAssessmentData = async (isManual = false) => {
  if (isSaving.value) {
    console.log("⏸️ 正在保存中，跳过本次保存");
    if (isManual) {
      ElMessage.warning("正在保存中，请稍候...");
    }
    return;
  }
  
  try {
    isSaving.value = true;
    
    const businessId = route.query.id;
    if (!businessId) {
      console.warn("⚠️ 没有业务ID，跳过保存");
      if (isManual) {
        ElMessage.error("缺少业务ID，无法保存");
      }
      return;
    }

    const assessmentData = {
      healthForm: JSON.parse(JSON.stringify(healthForm)),
      abilityForm: JSON.parse(JSON.stringify(abilityForm)),
      assessmentResults: JSON.parse(JSON.stringify(assessmentResults)),
    };

    console.log(`💾 ${isManual ? '手动' : '自动'}保存评估数据，业务ID:`, businessId);
    console.log("💾 数据摘要 - 疾病数:", assessmentData.healthForm.diseases?.length, 
                "用药数:", assessmentData.healthForm.medications?.length,
                "护理等级:", assessmentData.assessmentResults.nursingLevel);
    
    const response = await saveAssessmentDraft(businessId, JSON.stringify(assessmentData));
    
    // 🔥【新增】同时保存到 localStorage 作为备份
    try {
      localStorage.setItem(`assessment_draft_${businessId}`, JSON.stringify(assessmentData));
      console.log("💾 评估数据已备份到 localStorage");
    } catch (e) {
      console.warn("⚠️ localStorage 保存失败:", e);
    }
    
    // 🔥 记录保存时间 - 强制触发响应式更新
    lastAutoSaveTime.value = new Date();
    
    console.log("✅ 评估数据保存成功，时间:", lastAutoSaveTime.value.toLocaleTimeString());
    console.log("✅ lastAutoSaveTime 对象:", lastAutoSaveTime.value);
    
    // 🔥【优化】手动保存时显示成功提示，自动保存时不显示
    if (isManual) {
      ElMessage.success({
        message: `数据保存成功！保存时间: ${lastAutoSaveTime.value.toLocaleTimeString()}`,
        duration: 2000,
        showClose: true
      });
    }
  } catch (error) {
    console.error("❌ 评估数据保存失败:", error);
    console.error("❌ 错误详情:", error.message);
    
    // 🔥 手动保存失败时提示用户，自动保存失败时静默处理
    if (isManual) {
      ElMessage.error({
        message: `保存失败: ${error.message || '未知错误'}`,
        duration: 3000,
        showClose: true
      });
    }
  } finally {
    isSaving.value = false;
  }
};

const switchAssessmentTab = async (tabId) => {
  // 从健康评估(1)切换到能力评估(2)时，验证健康评估的必填项
  if (currentAssessmentTab.value === 1 && tabId === 2) {
    try {
      // 验证所有健康评估必填项
      if (healthForm.diseases.length === 0) {
        throw new Error("请填写疾病诊断信息");
      }

      // 验证用药信息（如果有用药）
      if (healthForm.medications.length > 0) {
        for (let med of healthForm.medications) {
          if (!med.name || med.name.toString().trim() === "") {
            throw new Error("请填写完整的用药名称");
          }
        }
      }

      // 验证风险评估项
      if (!healthForm.fallRisk) throw new Error("请选择跌倒风险");
      if (!healthForm.lostRisk) throw new Error("请选择走失风险");
      if (!healthForm.chokingRisk) throw new Error("请选择噎食风险");
      if (!healthForm.suicideRisk) throw new Error("请选择自杀风险");
      if (!healthForm.comaRisk) throw new Error("请选择昏迷风险");

      // 验证身体健康情况
      if (!healthForm.woundCondition) throw new Error("请选择伤口情况");
      if (!healthForm.selfCareAbility) throw new Error("请选择生活自理能力");

      // 🔥【已去除】体检报告不再必须上传
      // if (!medicalReportFiles.value || medicalReportFiles.value.length === 0) {
      //   throw new Error("请上传体检报告");
      // }

      // 🔥 验证通过后自动保存数据
      await autoSaveAssessmentData();
      
      // 验证通过，切换标签页
      currentAssessmentTab.value = tabId;
    } catch (error) {
      ElMessage.error(error.message || "有未提交的内容，请填写完整");
    }
  }
  // 从能力评估(2)切换到评估报告(3)时，验证能力评估的所有问题都已回答
  else if (currentAssessmentTab.value === 2 && tabId === 3) {
    try {
      // 验证所有能力评估问题都已回答
      const requiredFields = [
        "eating",
        "bathing",
        "grooming",
        "dressing",
        "toileting",
        "transferring",
        "walking",
        "communication",
        "cognition",
        "socialInteraction",
      ];

      for (const field of requiredFields) {
        if (!abilityForm[field]) {
          throw new Error(
            `请完成第${requiredFields.indexOf(field) + 1}题的回答`
          );
        }
      }

      // 计算评估分数
      calculateScore();

      // 🔥 验证通过后自动保存数据
      await autoSaveAssessmentData();

      // 验证通过，切换标签页
      currentAssessmentTab.value = tabId;
    } catch (error) {
      ElMessage.error(error.message || "有未完成的评估问题，请填写完整");
    }
  } else {
    // 其他切换直接执行
    currentAssessmentTab.value = tabId;
  }
};

// 返回上一步
const previousStep = async () => {
  // 🔥 如果当前在第二步，离开前自动保存评估数据
  if (currentStep.value === 2 && currentAssessmentTab.value === 1) {
    // 如果要从第二步回退到第一步，先保存评估数据
    await autoSaveAssessmentData();
  }

  // 第一步：在标签页间回退
  if (currentStep.value === 1 && currentApplyTab.value > 1) {
    currentApplyTab.value--;
    return;
  }

  // 第二步：在标签页间回退
  if (currentStep.value === 2 && currentAssessmentTab.value > 1) {
    currentAssessmentTab.value--;
    return;
  }

  // 步骤间回退
  if (currentStep.value > 1) {
    currentStep.value--;
    // 设置上一步骤的最后一个标签页
    if (currentStep.value === 1) currentApplyTab.value = applyTabs.value.length;
    if (currentStep.value === 2)
      currentAssessmentTab.value = assessmentTabs.value.length;
  }
};

// 身份证号解析
const handleIdCardBlur = () => {
  // 简单验证身份证格式
  if (basicForm.idCard && /^\d{17}[\dXx]$/.test(basicForm.idCard)) {
    // 解析性别
    const genderDigit = parseInt(basicForm.idCard.charAt(16));
    basicForm.gender = genderDigit % 2 === 1 ? "男" : "女";

    // 解析出生日期
    const birthYear = basicForm.idCard.substring(6, 10);
    const birthMonth = basicForm.idCard.substring(10, 12);
    const birthDay = basicForm.idCard.substring(12, 14);
    basicForm.birthDate = `${birthYear}-${birthMonth}-${birthDay}`;

    // 计算年龄
    const currentYear = new Date().getFullYear();
    basicForm.age = (currentYear - parseInt(birthYear)).toString();
  }
};

// 处理老人信息的函数
/**
 * 处理老人信息数据，填充到各个表单中
 * @param {Object} elderlyInfo - 老人信息对象
 */
const processElderlyInfo = (elderlyInfo) => {

  // ==================== 填充基本信息表单 ====================
  if (elderlyInfo.name) {
    basicForm.name = elderlyInfo.name;
  }
  if (elderlyInfo.idCard) {
    basicForm.idCard = elderlyInfo.idCard;
    handleIdCardBlur(); // 触发身份证信息自动解析
  }
  if (elderlyInfo.contact) {
    basicForm.contact = elderlyInfo.contact;
  }
  if (elderlyInfo.address) {
    basicForm.address = elderlyInfo.address;
  }
  if (elderlyInfo.ethnicity) {
    basicForm.ethnicity = getDictLabel(
      dictData.nationList,
      elderlyInfo.ethnicity
    );
  }
  if (elderlyInfo.politicalStatus) {
    basicForm.politicalStatus = getDictLabel(
      dictData.politicalList,
      elderlyInfo.politicalStatus
    );
  }
  if (elderlyInfo.religion) {
    basicForm.religion = getDictLabel(
      dictData.religionList,
      elderlyInfo.religion
    );
  }
  if (elderlyInfo.maritalStatus) {
    basicForm.maritalStatus = getDictLabel(
      dictData.maritalList,
      elderlyInfo.maritalStatus
    );
  }
  if (elderlyInfo.education) {
    basicForm.education = getDictLabel(
      dictData.educationList,
      elderlyInfo.education
    );
  }
  if (elderlyInfo.incomeSource) {
    basicForm.incomeSource = getDictLabel(
      dictData.incomeList,
      elderlyInfo.incomeSource
    );
  }
  if (elderlyInfo.hobbies) {
    basicForm.hobbies = getDictLabel(dictData.hobbyList, elderlyInfo.hobbies);
  }
  if (elderlyInfo.medicalInsurance !== undefined && elderlyInfo.medicalInsurance !== null) {
    basicForm.medicalInsurance = getDictLabel(
      dictData.medicalList,
      elderlyInfo.medicalInsurance
    );
  }
  if (elderlyInfo.medicalCardNo) {
    basicForm.medicalCardNo = elderlyInfo.medicalCardNo;
  }
  if (elderlyInfo.photo) {
    basicForm.photo = elderlyInfo.photo;
  }
  if (elderlyInfo.idCardFront) {
    basicForm.idCardFront = elderlyInfo.idCardFront;
  }
  if (elderlyInfo.idCardBack) {
    basicForm.idCardBack = elderlyInfo.idCardBack;
  }

  // ==================== 填充资料上传信息 ====================
  // 从数据库获取已上传的文件信息，填充到文件列表中
  
  
  // 处理一寸照片文件
  if (elderlyInfo.photo) {
    
    // 从URL中提取真实文件名
    const photoFileName = extractFileNameFromUrl(elderlyInfo.photo, "一寸照片.jpg");
    photoFiles.value = [{
      name: photoFileName,
      url: elderlyInfo.photo, // 数据库中的文件URL
      status: "success" // 标记为已成功上传
    }];
    
  }
  
  // 处理身份证人像面文件
  if (elderlyInfo.idCardFront) {
    
    // 从URL中提取真实文件名
    const idCardFrontFileName = extractFileNameFromUrl(elderlyInfo.idCardFront, "身份证人像面.jpg");
    idCardFrontFiles.value = [{
      name: idCardFrontFileName, 
      url: elderlyInfo.idCardFront, // 数据库中的文件URL
      status: "success" // 标记为已成功上传
    }];
    
  }
  
  // 处理身份证国徽面文件
  if (elderlyInfo.idCardBack) {
    
    // 从URL中提取真实文件名
    const idCardBackFileName = extractFileNameFromUrl(elderlyInfo.idCardBack, "身份证国徽面.jpg");
    idCardBackFiles.value = [{
      name: idCardBackFileName,
      url: elderlyInfo.idCardBack, // 数据库中的文件URL
      status: "success" // 标记为已成功上传
    }];
    
  }
 

  // ==================== 填充家属信息 ====================
  
  
  // 尝试获取老人ID，支持多种字段名
  const elderlyId = elderlyInfo.id || elderlyInfo.elderlyId || elderlyInfo.elderly_id || elderlyInfo.ID;
  
  // 如果后端返回了家属信息，则使用
  if (elderlyInfo.familyMembers && elderlyInfo.familyMembers.length > 0) {
    familyForm.members = elderlyInfo.familyMembers.map(member => ({
      name: member.name || "",
      contact: member.contact || "",
      relationship: member.relationship || ""
    }));
    
  } else if (elderlyId) {
    // 如果后端没有返回家属信息，但有老人ID，则主动从数据库获取家属信息
    loadFamilyMembersByElderlyId(elderlyId);
  } else {
    // 没有可用的老人ID，无法从数据库加载家属信息
    // 根据业务需要，这里可以提示用户或静默跳过
  }

  // ==================== 填充住房情况信息 ====================
  if (elderlyInfo.housingInfo) {
    const housing = elderlyInfo.housingInfo;
    if (housing.bedNo) {
      configForm.selectedBed = `${housing.buildingNo || ''}${housing.floorNo || ''}${housing.roomNo || ''}-${housing.bedNo}`;
    }
  }

  // ==================== 填充合同信息 ====================
  
  if (elderlyInfo.contractInfo && Object.keys(elderlyInfo.contractInfo).length > 0) {
    
    const contract = elderlyInfo.contractInfo;
    if (contract.contractNumber) {
      contractForm.contractNumber = contract.contractNumber;
    }
    if (contract.contractName) {
      contractForm.contractName = contract.contractName;
    }
    // 尝试多种可能的字段名
    if (contract.contractStartDate || contract.contractStartTime || contract.startDate || contract.startTime) {
      contractForm.contractStartTime = normalizeToYMD(
        contract.contractStartDate || contract.contractStartTime || contract.startDate || contract.startTime
      );
    }
    if (contract.contractEndDate || contract.contractEndTime || contract.endDate || contract.endTime) {
      contractForm.contractEndTime = normalizeToYMD(
        contract.contractEndDate || contract.contractEndTime || contract.endDate || contract.endTime
      );
    }
    if (contract.contractFile || contract.file || contract.contractFileUrl) {
      contractForm.contractFile = contract.contractFile || contract.file || contract.contractFileUrl;
    }
    if (contract.signDate || contract.signTime) {
      contractForm.signDate = normalizeToYMD(contract.signDate || contract.signTime);
    }
    if (contract.partyCName) {
      contractForm.partyCName = contract.partyCName;
    }
    if (contract.partyCcontact) {
      contractForm.partyCcontact = contract.partyCcontact;
    }
    
  } else {
    
    // 检查是否有直接的合同字段，尝试多种可能的字段名
    if (elderlyInfo.contractNumber) {
      contractForm.contractNumber = elderlyInfo.contractNumber;
    }
    // 不再从老人基础信息回填合同名称，合同名称应来源于合同表或显式合同参数
    if (elderlyInfo.contractStartDate || elderlyInfo.contractStartTime || elderlyInfo.startDate || elderlyInfo.startTime) {
      contractForm.contractStartTime = normalizeToYMD(
        elderlyInfo.contractStartDate || elderlyInfo.contractStartTime || elderlyInfo.startDate || elderlyInfo.startTime
      );
    }
    if (elderlyInfo.contractEndDate || elderlyInfo.contractEndTime || elderlyInfo.endDate || elderlyInfo.endTime) {
      contractForm.contractEndTime = normalizeToYMD(
        elderlyInfo.contractEndDate || elderlyInfo.contractEndTime || elderlyInfo.endDate || elderlyInfo.endTime
      );
    }
    if (elderlyInfo.contractFile || elderlyInfo.file || elderlyInfo.contractFileUrl) {
      contractForm.contractFile = elderlyInfo.contractFile || elderlyInfo.file || elderlyInfo.contractFileUrl;
    }
    // 不再从老人基础信息的签约日期回填合同签约日期，合同签约日期应来源于合同表
    if (elderlyInfo.partyCName) {
      contractForm.partyCName = elderlyInfo.partyCName;
    }
    if (elderlyInfo.partyCcontact) {
      contractForm.partyCcontact = elderlyInfo.partyCcontact;
    }
    
    // 如果还是没有合同信息，使用基本信息填充
    if (!contractForm.contractNumber && elderlyInfo.checkInNo) {
    contractForm.contractNumber = elderlyInfo.checkInNo;
    }
    if (!contractForm.partyCName && elderlyInfo.name) {
      contractForm.partyCName = elderlyInfo.name;
    }
    if (!contractForm.partyCcontact && elderlyInfo.contact) {
      contractForm.partyCcontact = elderlyInfo.contact;
    }
    // 不设置默认“今天”为签约日期，避免覆盖合同表实际签约时间
    
  }
  
  // 确保合同表单有默认值
  if (!contractForm.contractNumber && elderlyInfo.checkInNo) {
    contractForm.contractNumber = elderlyInfo.checkInNo;
  }
  // 不设置默认“今天”为签约日期，确保仅由合同数据决定

  // 日期字段回退：若合同起止时间仍为空，尝试使用费用起止日期
  if (!contractForm.contractStartTime && elderlyInfo.feeInfo && elderlyInfo.feeInfo.feeStartDate) {
    contractForm.contractStartTime = normalizeToYMD(elderlyInfo.feeInfo.feeStartDate);
  }
  if (!contractForm.contractEndTime && elderlyInfo.feeInfo && elderlyInfo.feeInfo.feeEndDate) {
    contractForm.contractEndTime = normalizeToYMD(elderlyInfo.feeInfo.feeEndDate);
  }
  if (!contractForm.partyCName && elderlyInfo.name) {
    contractForm.partyCName = elderlyInfo.name;
  }
  if (!contractForm.partyCcontact && elderlyInfo.contact) {
    contractForm.partyCcontact = elderlyInfo.contact;
  }
  
  

  // ==================== 填充费用信息 ====================
  if (elderlyInfo.feeInfo) {
    const fee = elderlyInfo.feeInfo;
    if (fee.deposit) {
      configForm.deposit = fee.deposit;
    }
    if (fee.nursingFee) {
      configForm.nursingFee = fee.nursingFee;
    }
    if (fee.bedFee) {
      configForm.bedFee = fee.bedFee;
    }
    if (fee.otherFee) {
      configForm.otherFee = fee.otherFee;
    }
    if (fee.medicalInsurancePayment) {
      configForm.insurancePayment = fee.medicalInsurancePayment;
    }
    if (fee.governmentSubsidy) {
      configForm.governmentSubsidy = fee.governmentSubsidy;
    }
    if (fee.feeStartDate && fee.feeEndDate) {
      configForm.feePeriod = [fee.feeStartDate, fee.feeEndDate];
    }
  }

  // ==================== 填充评估信息 ====================
  if (elderlyInfo.assessmentInfo) {
    const assessment = elderlyInfo.assessmentInfo;
    if (assessment.selfCareScore) {
      assessmentResults.selfCareScore = assessment.selfCareScore;
    }
    if (assessment.mentalStateScore) {
      assessmentResults.mentalStateScore = assessment.mentalStateScore;
    }
    if (assessment.socialParticipationScore) {
      assessmentResults.socialParticipationScore = assessment.socialParticipationScore;
    }
    if (assessment.totalScore) {
      assessmentResults.totalScore = assessment.totalScore;
    }
    if (assessment.nursingLevel) {
      assessmentResults.nursingLevel = assessment.nursingLevel;
    }
  }

  // 🔥【关键修复】不在这里填充默认值！
  // 原因：assessmentInfo 是主表的评估分数，但详细数据在 assessment_draft_json 中
  // 即使 assessmentInfo 为空，也可能有草稿数据
  // 正确做法：先加载草稿数据，然后在 onMounted 中根据模式决定是否填充默认值
  
  // 🔥【已禁用】不再填充默认值，所有步骤都不填充默认值
  // if (isViewMode.value) {
  //   populateViewDefaultsIfEmpty();
  // }

  // ==================== 填充入住配置信息 ====================
  // 处理护理等级 - 将数字转换为汉字
  if (elderlyInfo.nursingLevelId) {
    const nursingLevelMap = {
      '1': '一级护理',
      '2': '二级护理', 
      '3': '三级护理',
      '4': '自理'
    };
    configForm.nursingLevel = nursingLevelMap[elderlyInfo.nursingLevelId] || elderlyInfo.nursingLevelId;
  }
  
  // 处理入住期限
  if (elderlyInfo.checkInStartTime && elderlyInfo.checkInEndTime) {
    configForm.stayPeriod = [elderlyInfo.checkInStartTime, elderlyInfo.checkInEndTime];
  } else if (elderlyInfo.checkInStartTime) {
    // 如果只有开始时间，设置默认结束时间（一年后）
    const startDate = new Date(elderlyInfo.checkInStartTime);
    const endDate = new Date(startDate);
    endDate.setFullYear(endDate.getFullYear() + 1);
    configForm.stayPeriod = [
      elderlyInfo.checkInStartTime,
      endDate.toISOString().split('T')[0]
    ];
  }

  // 🔥【已修复】删除强制跳转到第5步的代码
  // 原因：步骤跳转应该由路由参数和审批记录控制，不应该在这里强制跳转
  // currentStep.value 的值应该在 onMounted 中根据 targetStep 正确设置
  // 如果在这里强制设为5，会覆盖从审批记录获取的正确步骤号
};

// ==================== 默认值填充函数 ====================
/**
 * 填充测试默认值，方便测试时减少手动输入
 */
const fillDefaultTestValues = () => {
  console.log("填充测试默认值...");
  
  // 基本信息默认值
  if (!basicForm.name) basicForm.name = "张三";
  if (!basicForm.idCard) basicForm.idCard = "110101195001011234";
  if (!basicForm.gender) basicForm.gender = "男";
  if (!basicForm.birthDate) basicForm.birthDate = "1950-01-01";
  if (!basicForm.age) basicForm.age = "74";
  if (!basicForm.contact) basicForm.contact = "13800138000";
  if (!basicForm.address) basicForm.address = "北京市朝阳区测试街道123号";
  // 🔥 使用字典中实际存在的value值（不是label）
  if (!basicForm.ethnicity) basicForm.ethnicity = "0";  // 0=汉族
  if (!basicForm.politicalStatus) basicForm.politicalStatus = "3";  // 3=群众
  if (!basicForm.religion) basicForm.religion = "0";  // 0=佛教
  if (!basicForm.maritalStatus) basicForm.maritalStatus = "1";  // 1=已婚
  if (!basicForm.education) basicForm.education = "2";  // 2=初中
  if (!basicForm.incomeSource) basicForm.incomeSource = "2";  // 2=社会补助
  if (!basicForm.hobbies) basicForm.hobbies = "2";  // 2=跑步
  if (!basicForm.medicalInsurance) basicForm.medicalInsurance = "0";  // 0=社会医疗保险
  if (!basicForm.medicalCardNo) basicForm.medicalCardNo = "123456789012345678";

  // 家属信息默认值
  if (!familyForm.members || familyForm.members.length === 0) {
    familyForm.members = [
      { name: "李四", contact: "13900139000", relationship: "1" },  // 1=配偶亲属关系
      { name: "张五", contact: "13700137000", relationship: "0" }   // 0=直系亲属关系
    ];
  } else {
    // 如果已有家属信息但为空，则填充默认值
    familyForm.members.forEach(member => {
      if (!member.name) member.name = "李四";
      if (!member.contact) member.contact = "13900139000";
      if (!member.relationship) member.relationship = "1";  // 1=配偶亲属关系
    });
  }

  // 健康信息默认值
  if (!healthForm.diseases || healthForm.diseases.length === 0) {
    healthForm.diseases = ["高血压", "糖尿病"];
  }
  if (!healthForm.medications || healthForm.medications.length === 0) {
    healthForm.medications = ["降压药", "降糖药"];
  }
  // 🔥 使用表单中定义的选项值（"无"、"发生过1次"等）
  if (!healthForm.fallRisk) healthForm.fallRisk = "无";
  if (!healthForm.lostRisk) healthForm.lostRisk = "无";
  if (!healthForm.chokingRisk) healthForm.chokingRisk = "无";
  if (!healthForm.suicideRisk) healthForm.suicideRisk = "无";
  if (!healthForm.comaRisk) healthForm.comaRisk = "无";
  if (!healthForm.woundCondition) healthForm.woundCondition = "无";
  if (!healthForm.specialMedicalServices || healthForm.specialMedicalServices.length === 0) {
    healthForm.specialMedicalServices = ["血压监测"];
  }
  if (!healthForm.selfCareAbility) healthForm.selfCareAbility = "部分自理";
  if (!healthForm.dementiaSigns || healthForm.dementiaSigns.length === 0) {
    healthForm.dementiaSigns = ["记忆力减退"];
  }
  if (!healthForm.otherDementiaSigns) healthForm.otherDementiaSigns = "无其他症状";

  // 能力评估默认值 - 使用表单中定义的选项值（A/B/C/D/E）
  if (!abilityForm.eating) abilityForm.eating = "B";  // B=在他人语言指导或照看下完成
  if (!abilityForm.bathing) abilityForm.bathing = "C";  // C=需要他人协助，但以自身完成为主
  if (!abilityForm.grooming) abilityForm.grooming = "B";
  if (!abilityForm.dressing) abilityForm.dressing = "B";
  if (!abilityForm.toileting) abilityForm.toileting = "B";
  if (!abilityForm.transferring) abilityForm.transferring = "B";
  if (!abilityForm.walking) abilityForm.walking = "C";
  if (!abilityForm.communication) abilityForm.communication = "B";
  if (!abilityForm.cognition) abilityForm.cognition = "C";
  if (!abilityForm.socialInteraction) abilityForm.socialInteraction = "B";

  // 配置信息默认值
  if (!configForm.stayPeriod || configForm.stayPeriod.length === 0) {
    const today = new Date();
    const nextYear = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate());
    configForm.stayPeriod = [
      today.toISOString().split('T')[0],
      nextYear.toISOString().split('T')[0]
    ];
  }
  // 🔥 护理等级使用数据库ID，从 nursingLevelList 中选择第一个可用的
  if (!configForm.nursingLevel && dictData.nursingLevelList.length > 0) {
    configForm.nursingLevel = dictData.nursingLevelList[0].value;
  }
  if (!configForm.feePeriod || configForm.feePeriod.length === 0) {
    const today = new Date();
    const nextYear = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate());
    configForm.feePeriod = [
      today.toISOString().split('T')[0],
      nextYear.toISOString().split('T')[0]
    ];
  }
  if (!configForm.deposit) configForm.deposit = 5000;
  if (!configForm.nursingFee) configForm.nursingFee = 2000;
  if (!configForm.bedFee) configForm.bedFee = 1500;
  if (!configForm.otherFee) configForm.otherFee = 500;
  if (!configForm.insurancePayment) configForm.insurancePayment = 800;
  if (!configForm.governmentSubsidy) configForm.governmentSubsidy = 200;

  // 合同信息默认值
  if (!contractForm.contractNumber) {
    contractForm.contractNumber = `HT${new Date().getTime()}`;
  }
  if (!contractForm.contractName) contractForm.contractName = "养老服务合同";
  if (!contractForm.contractStartTime) {
    contractForm.contractStartTime = new Date().toISOString().split('T')[0];
  }
  if (!contractForm.contractEndTime) {
    const nextYear = new Date();
    nextYear.setFullYear(nextYear.getFullYear() + 1);
    contractForm.contractEndTime = nextYear.toISOString().split('T')[0];
  }
  if (!contractForm.signDate) {
    contractForm.signDate = new Date().toISOString().split('T')[0];
  }
  if (!contractForm.partyCName) contractForm.partyCName = basicForm.name;
  if (!contractForm.partyCcontact) contractForm.partyCcontact = basicForm.contact;
  
  // 资料上传默认值
  if (!photoFiles.value || photoFiles.value.length === 0) {
    photoFiles.value = [{
      uid: "default-photo",
      name: "一寸照片示例.jpg",
      url: "/profile/template/photo-sample.jpg",
      status: "success"
    }];
  }
  if (!idCardFrontFiles.value || idCardFrontFiles.value.length === 0) {
    idCardFrontFiles.value = [{
      uid: "default-id-front",
      name: "身份证人像面示例.jpg",
      url: "/profile/template/id-card-front-sample.jpg",
      status: "success"
    }];
  }
  if (!idCardBackFiles.value || idCardBackFiles.value.length === 0) {
    idCardBackFiles.value = [{
      uid: "default-id-back",
      name: "身份证国徽面示例.jpg",
      url: "/profile/template/id-card-back-sample.jpg",
      status: "success"
    }];
  }

  console.log("测试默认值填充完成");
};

// ==================== 生命周期和初始化 ====================
/**
 * 页面挂载时初始化
 */
onMounted(async () => {
  try {
    console.log("checkInForm组件开始初始化...");
    
    // 🔥 初始化必要的字段（防止null/undefined错误）
    initializeRequiredFields();
    
    // 🔥【调试】打印所有query参数
    console.log("🔍 当前路由query参数:", route.query);
    
    // 🔥 保存目标步骤号（从待办任务传递过来的）
    let targetStep = null;
    if (route.query.step) {
      targetStep = parseInt(route.query.step);
      console.log("🎯 目标步骤:", targetStep, "审批模式:", isApprovalMode.value, "查看模式:", isViewMode.value);
    } else {
      console.log("⚠️ route.query.step 不存在，targetStep = null");
    }
    
    // 🔥【新增】查看模式下，设置用户可以查看的最大步骤
    if (isViewMode.value && route.query.step) {
      maxViewableStep.value = parseInt(route.query.step);
      console.log("✅ 查看模式 - 用户可查看的最大步骤:", maxViewableStep.value);
    }
    
    const elderlyInfoStr = route.query.elderlyInfo;
    const managementId = route.query.id; // 从我的代办传递的业务ID

    if (elderlyInfoStr) {
      try {
        const elderlyInfo = JSON.parse(elderlyInfoStr);
        console.log("解析老人信息成功:", elderlyInfo);

        // 先尝试加载字典数据
        try {
          await getDictList();
          console.log("字典数据加载成功");
        } catch (dictError) {
          console.error("字典数据加载失败:", dictError);
          // 即使字典数据加载失败，也继续执行后续逻辑
        }

        // 🔥 加载护理等级和床位数据
        try {
          await Promise.all([
            loadNursingLevels(),
            loadBedList()
          ]);
          console.log("✅ 护理等级和床位数据加载成功");
        } catch (error) {
          console.error("❌ 加载护理等级或床位数据失败:", error);
        }

        // 处理老人信息
        processElderlyInfo(elderlyInfo);

        // 🔥【关键修复】如果有managementId，先加载评估草稿数据
        const mgmtId = elderlyInfo.id || elderlyInfo.checkInManagementId || managementId;
        if (mgmtId) {
          try {
            await loadAssessmentDraft(mgmtId);
            console.log("✅ 评估草稿数据加载成功");
          } catch (e) {
            console.warn("⚠️ 评估草稿数据加载失败:", e);
          }
        }

        // 🔥【关键修复】已禁用默认值填充，所有步骤都不填充默认值
        // 用户需要从空白开始填写，确保数据真实性
        // if (isViewMode.value) {
        //   populateDefaultAssessmentIfEmpty();
        //   populateViewDefaultsIfEmpty();
        // }

        // 若未带合同文件且可解析出老人ID，则根据老人ID从合同表加载合同
        try {
          const elderlyId = elderlyInfo.id || elderlyInfo.elderlyId || elderlyInfo.elderly_id || elderlyInfo.ID;
          if (elderlyId) {
            await loadContractByElderlyId(elderlyId);
          }
        } catch (e) {
          console.warn("合同加载失败:", e);
        }
      } catch (error) {
        console.error("解析老人信息失败:", error);
        ElMessage.error("加载老人信息失败");
      }
    } else if (managementId) {
      // 从我的代办跳转过来，根据业务ID加载入住管理数据
      try {
        console.log("从我的代办跳转，开始加载入住管理数据，ID:", managementId);
        
        // 先加载字典数据
        try {
          await getDictList();
          console.log("字典数据加载成功");
        } catch (dictError) {
          console.error("字典数据加载失败:", dictError);
        }

        // 🔥 加载护理等级和床位数据
        try {
          await Promise.all([
            loadNursingLevels(),
            loadBedList()
          ]);
          console.log("✅ 护理等级和床位数据加载成功");
        } catch (error) {
          console.error("❌ 加载护理等级或床位数据失败:", error);
        }

        // 根据业务ID获取入住管理详细数据
        const response = await getManagement(managementId);
        console.log("获取入住管理数据成功:", response);
        
        if (response && response.data) {
          const managementData = response.data;
          
          // 构建老人信息对象，参考management/index.vue的handleView方法
          const elderlyInfo = {
            // 基本信息
            elderlyId: managementData.elderlyId,
            name: managementData.elderly?.name,
            idCard: managementData.elderly?.idCard,
            contact: managementData.elderly?.contact,
            address: managementData.elderly?.address,
            ethnicity: managementData.elderly?.ethnicity,
            politicalStatus: managementData.elderly?.politicalStatus,
            religion: managementData.elderly?.religion,
            maritalStatus: managementData.elderly?.maritalStatus,
            education: managementData.elderly?.education,
            incomeSource: managementData.elderly?.incomeSource,
            hobbies: managementData.elderly?.hobbies,
            medicalInsurance: managementData.elderly?.medicalInsurance,
            medicalCardNo: managementData.elderly?.medicalCardNo,
            photo: managementData.elderly?.photo,
            idCardFront: managementData.elderly?.idCardFront,
            idCardBack: managementData.elderly?.idCardBack,
            
            // 入住信息
            checkInNo: managementData.checkInNo,
            checkInStartTime: managementData.checkInStartTime,
            checkInEndTime: managementData.checkInEndTime,
            nursingLevelId: managementData.nursingLevelId,
            bedId: managementData.bedId,
            
            // 家属信息
            familyMembers: managementData.elderly?.familyMembers || [],
            
            // 住房情况
            housingInfo: {
              bedNo: managementData.bed?.bedNo,
              roomNo: managementData.bed?.roomNo,
              buildingNo: managementData.bed?.buildingNo,
              floorNo: managementData.bed?.floorNo,
              bedType: managementData.bed?.bedType,
              bedStatus: managementData.bed?.bedStatus
            },
            
            // 合同情况
            contractInfo: {
              contractNumber: managementData.contractNumber,
              contractName: managementData.contractName,
              contractStartDate: managementData.contractStartDate,
              contractEndDate: managementData.contractEndDate,
              signDate: managementData.signDate,
              partyCName: managementData.partyCName,
              partyCcontact: managementData.partyCcontact,
              contractStatus: managementData.contractStatus,
              contractFile: managementData.contractFile
            },
            
            // 费用信息
            feeInfo: {
              deposit: managementData.deposit,
              nursingFee: managementData.nursingFee,
              bedFee: managementData.bedFee,
              otherFee: managementData.otherFee,
              medicalInsurancePayment: managementData.medicalInsurancePayment,
              governmentSubsidy: managementData.governmentSubsidy,
              feeStartDate: managementData.feeStartDate,
              feeEndDate: managementData.feeEndDate
            },
            
            // 评估信息
            assessmentInfo: {
              selfCareScore: managementData.selfCareScore,
              mentalStateScore: managementData.mentalStateScore,
              socialParticipationScore: managementData.socialParticipationScore,
              totalScore: managementData.totalScore,
              nursingLevel: managementData.nursingLevel,
              assessmentDate: managementData.assessmentDate
            }
          };
          
          console.log("构建完成的老人信息对象:", elderlyInfo);
          
          // 处理老人信息
          processElderlyInfo(elderlyInfo);
          
          // 🔥【关键修复】先加载评估草稿数据，再填充默认值
          // 这样可以确保真实数据优先，默认值只用于填补空白
          try {
            await loadAssessmentDraft(managementId);
            console.log("✅ 评估草稿数据加载成功");
          } catch (e) {
            console.warn("⚠️ 评估草稿数据加载失败:", e);
            // 如果没有草稿数据，继续执行，不影响正常流程
          }
          
          // 🔥【关键修复】已禁用默认值填充，所有步骤都不填充默认值
          // if (isViewMode.value) {
          //   populateDefaultAssessmentIfEmpty();
          //   populateViewDefaultsIfEmpty();
          // }
          
          // 加载合同信息
          try {
            const elderlyId = elderlyInfo.elderlyId;
            if (elderlyId) {
              await loadContractByElderlyId(elderlyId);
            }
          } catch (e) {
            console.warn("合同加载失败:", e);
          }
          
          ElMessage.success("成功加载入住管理数据");
        } else {
          console.error("获取入住管理数据失败，响应数据为空");
          ElMessage.error("获取入住管理数据失败");
        }
      } catch (error) {
        console.error("加载入住管理数据失败:", error);
        ElMessage.error("加载入住管理数据失败: " + (error.message || "未知错误"));
      }
    } else {
      // 如果没有老人信息参数和业务ID，仍然加载字典数据
      try {
        await getDictList();
        console.log("字典数据加载成功");
      } catch (error) {
        console.error("字典数据加载失败:", error);
        // 即使字典数据加载失败，也继续执行后续逻辑
      }

      // 🔥 加载护理等级和床位数据
      try {
        await Promise.all([
          loadNursingLevels(),
          loadBedList()
        ]);
        console.log("✅ 护理等级和床位数据加载成功");
      } catch (error) {
        console.error("❌ 加载护理等级或床位数据失败:", error);
      }
      
      // 🔥【已禁用】不再填充测试默认值，用户需要从空白开始填写
      // if (!isApprovalMode.value) {
      //   fillDefaultTestValues();
      // }
    }
    
    // 🔥【关键修复】数据加载完成后，应用目标步骤
    // 这样可以确保即使数据加载过程中有任何步骤重置，最终都会跳转到正确的步骤
    if (targetStep !== null) {
      if (isApprovalMode.value) {
        // 🔥【新增】审批模式：检查用户权限，只能跳转到自己负责的步骤
        const userStep = getCurrentUserStep();
        if (targetStep === userStep) {
          currentStep.value = targetStep;
          console.log("✅ 审批模式 - 权限验证通过，跳转到第", currentStep.value, "步");
        } else {
          currentStep.value = userStep;
          console.warn("⚠️ 权限不足！用户只能处理第", userStep, "步，已自动跳转");
          ElMessage.warning(`您只有权限处理步骤${userStep}（${steps[userStep - 1]?.label}）`);
        }
      } else if (isViewMode.value) {
        // 🔥【修改】查看模式：跳转到用户处理的那一步（从审批记录获取）
        currentStep.value = targetStep;
        console.log("✅ 查看模式 - 跳转到第", currentStep.value, "步（targetStep=" + targetStep + "）");
        console.log("🔍 currentStep.value:", currentStep.value, "步骤名称:", steps.value.find(s => s.id === currentStep.value)?.label);
      } else {
        // 普通查看模式：从第一步开始，但记录目标步骤供参考
        currentStep.value = 1;
        console.log("✅ 普通模式 - 从第1步开始（原目标步骤:", targetStep, "）");
      }
    } else if (isViewMode.value) {
      // 🔥【新增】查看模式下，即使targetStep为null，也要使用maxViewableStep跳转
      currentStep.value = maxViewableStep.value;
      console.log("✅ 查看模式 - targetStep为null，使用maxViewableStep跳转到第", currentStep.value, "步");
      console.log("🔍 currentStep.value:", currentStep.value, "步骤名称:", steps.value.find(s => s.id === currentStep.value)?.label);
    }
    
    // 🔥【新增】最终调试日志：打印当前步骤和显示内容匹配情况
    console.log("🔍 最终currentStep.value:", currentStep.value);
    console.log("🔍 steps数组:", steps.value.map(s => ({id: s.id, label: s.label})));

    // 🔥【新增】加载审批记录
    await loadApprovalRecords();
    
    // 🔥【新增】加载评估数据（如果存在）
    if (checkInManagementId) {
      await loadAssessmentData(checkInManagementId);
    }
    
    // 🔥【新增】初始化自动保存监听器
    setupAutoSaveWatcher();
    console.log("✅ 自动保存监听器已初始化");
    
    console.log("checkInForm组件初始化完成");
  } catch (error) {
    console.error("组件初始化过程中发生错误:", error);
  }

  // 🔥 已禁用"未保存数据"提示功能，避免在处理数据时频繁弹出干扰
  // 监听页面离开（浏览器刷新/关闭）
  // const beforeUnloadHandler = (e) => {
  //   if (hasUnsavedChanges.value) {
  //     e.preventDefault();
  //     e.returnValue = '';
  //   }
  // };
  // window.addEventListener('beforeunload', beforeUnloadHandler);

  // 任意输入更改即标记为未保存
  // const markDirty = () => { hasUnsavedChanges.value = true; };
  // window.addEventListener('input', markDirty, true);

  // 在组件实例上保存，便于卸载时移除
  // onUnmounted(() => {
  //   window.removeEventListener('beforeunload', beforeUnloadHandler);
  //   window.removeEventListener('input', markDirty, true);
  // });
});

// 🔥 路由离开前的守卫：自动保存评估数据
onBeforeRouteLeave(async (to, from, next) => {
  // 如果当前在第二步（入住评估），自动保存评估数据
  if (currentStep.value === 2) {
    console.log("🚪 路由离开，自动保存评估数据...");
    await autoSaveAssessmentData();
  }
  next();
});

// 🔥 组件卸载前：自动保存评估数据
onBeforeUnmount(async () => {
  // 如果当前在第二步（入住评估），自动保存评估数据
  if (currentStep.value === 2) {
    console.log("🗑️ 组件卸载，自动保存评估数据...");
    await autoSaveAssessmentData();
  }
});

// ==================== 家属管理函数 ====================
/**
 * 根据老人ID获取家属信息
 * @param {Number} elderlyId - 老人ID
 */
const loadFamilyMembersByElderlyId = async (elderlyId) => {
  
  try {
    const response = await listMember({ elderlyId: elderlyId });
    
    if (response && response.rows && response.rows.length > 0) {
      familyForm.members = response.rows.map(member => ({
        name: member.name || "",
        contact: member.contact || "",
        relationship: member.relationship || ""
      }));
      ElMessage.success(`成功加载${response.rows.length}条家属信息`);
    } else {
      // 如果没有家属信息，保持默认的空状态
      familyForm.members = [{ name: "", contact: "", relationship: "" }];
      ElMessage.info("该老人暂无家属信息，请手动添加");
    }
  } catch (error) {
    ElMessage.warning("获取家属信息失败，请手动添加");
    // 出错时保持默认的空状态
    familyForm.members = [{ name: "", contact: "", relationship: "" }];
  }
};

// ==================== 合同加载函数 ====================
/**
 * 根据老人ID从合同表加载最新合同，并填充到合同表单
 * 优先取包含文件URL的记录
 */
const loadContractByElderlyId = async (elderlyId) => {
  try {
    const resp = await listContract({ elderlyId, pageNum: 1, pageSize: 1, orderByColumn: 'createTime', isAsc: 'desc' });
    const rows = (resp && (resp.rows || resp.data || [])) || [];
    const first = Array.isArray(rows) ? rows[0] : null;
    if (first) {
      // 兼容多种字段名
      const fileUrl = first.contractFile || first.file || first.contractFileUrl || first.fileUrl;
      if (fileUrl) {
        contractForm.contractFile = fileUrl;
      }
      if (first.contractNumber) contractForm.contractNumber = contractForm.contractNumber || first.contractNumber;
      // 合同名称以合同表为准，若合同表有值则强制覆盖
      if (first.contractName) contractForm.contractName = first.contractName;
      if (first.signDate) contractForm.signDate = contractForm.signDate || normalizeToYMD(first.signDate);
      if (first.contractStartTime || first.contractStartDate) {
        contractForm.contractStartTime = contractForm.contractStartTime || normalizeToYMD(first.contractStartTime || first.contractStartDate);
      }
      if (first.contractEndTime || first.contractEndDate) {
        contractForm.contractEndTime = contractForm.contractEndTime || normalizeToYMD(first.contractEndTime || first.contractEndDate);
      }
    }
  } catch (error) {
    console.error('根据老人ID加载合同失败', error);
  }
};

/**
 * 🔥【新增】加载评估草稿数据（从assessment_draft_json字段）
 */
const loadAssessmentDraft = async (checkInManagementId) => {
  try {
    console.log("🔍 开始加载评估草稿数据，入住管理ID:", checkInManagementId);
    console.log("📊 当前healthForm状态:", JSON.parse(JSON.stringify(healthForm)));
    console.log("📊 当前abilityForm状态:", JSON.parse(JSON.stringify(abilityForm)));
    console.log("📊 当前assessmentResults状态:", JSON.parse(JSON.stringify(assessmentResults)));
    
    // 🔥【关键修复】设置标志位，防止watch触发重新计算
    isRestoringDraft.value = true;
    
    const response = await getAssessmentDraft(checkInManagementId);
    console.log("🌐 API响应完整数据:", response);
    
    // 🔥【新增】如果后端返回为空，尝试从 localStorage 恢复
    let draftJson = response?.data;
    if (!draftJson || draftJson === null || draftJson === undefined) {
      console.warn("⚠️ 后端未返回评估草稿数据，尝试从 localStorage 恢复...");
      try {
        const localData = localStorage.getItem(`assessment_draft_${checkInManagementId}`);
        if (localData) {
          draftJson = localData;
          console.log("✅ 从 localStorage 成功恢复评估数据");
        } else {
          console.warn("⚠️ localStorage 中也没有找到备份数据");
        }
      } catch (e) {
        console.error("❌ localStorage 读取失败:", e);
      }
    }
    
    // 🔥【修改】无论数据来自后端还是 localStorage，都统一处理
    if (draftJson && draftJson !== null && draftJson !== undefined) {
      console.log("✅ 获取到评估草稿数据");
      console.log("📝 draftJson类型:", typeof draftJson);
      console.log("📝 draftJson是否为null:", draftJson === null);
      console.log("📝 draftJson是否为undefined:", draftJson === undefined);
      console.log("📦 获取到的评估草稿JSON:", draftJson);
      console.log("📦 草稿JSON类型:", typeof draftJson);
      console.log("📦 草稿JSON长度:", typeof draftJson === 'string' ? draftJson.length : 'N/A');
      
      // 解析JSON数据
      const draftData = typeof draftJson === 'string' ? JSON.parse(draftJson) : draftJson;
      console.log("📋 解析后的评估草稿数据:", draftData);
      console.log("📋 draftData.healthForm是否存在:", !!draftData.healthForm);
      console.log("📋 draftData.abilityForm是否存在:", !!draftData.abilityForm);
      console.log("📋 draftData.assessmentResults是否存在:", !!draftData.assessmentResults);
      
      // 🔥【关键修复】完全替换数据，而不是浅合并
      // 这样可以确保数组和嵌套对象被正确恢复
      if (draftData.healthForm) {
        console.log("🔄 开始恢复healthForm数据...");
        // 清空现有数据
        Object.keys(healthForm).forEach(key => {
          if (Array.isArray(healthForm[key])) {
            healthForm[key] = [];
          } else if (typeof healthForm[key] === 'object' && healthForm[key] !== null) {
            healthForm[key] = {};
          } else {
            healthForm[key] = "";
          }
        });
        // 深度复制草稿数据
        Object.keys(draftData.healthForm).forEach(key => {
          if (Array.isArray(draftData.healthForm[key])) {
            healthForm[key] = JSON.parse(JSON.stringify(draftData.healthForm[key]));
          } else {
            healthForm[key] = draftData.healthForm[key];
          }
        });
        console.log("✅ 恢复健康评估数据完成:", JSON.parse(JSON.stringify(healthForm)));
      } else {
        console.warn("⚠️ 草稿数据中没有healthForm");
      }
      
      // 恢复能力评估数据
      if (draftData.abilityForm) {
        console.log("🔄 开始恢复abilityForm数据...");
        Object.keys(abilityForm).forEach(key => {
          abilityForm[key] = "";
        });
        Object.assign(abilityForm, draftData.abilityForm);
        console.log("✅ 恢复能力评估数据完成:", JSON.parse(JSON.stringify(abilityForm)));
      } else {
        console.warn("⚠️ 草稿数据中没有abilityForm");
      }
      
      // 恢复评估结果
      if (draftData.assessmentResults) {
        console.log("🔄 开始恢复assessmentResults数据...");
        Object.keys(assessmentResults).forEach(key => {
          if (Array.isArray(assessmentResults[key])) {
            assessmentResults[key] = [];
          } else {
            assessmentResults[key] = "";
          }
        });
        Object.keys(draftData.assessmentResults).forEach(key => {
          if (Array.isArray(draftData.assessmentResults[key])) {
            assessmentResults[key] = JSON.parse(JSON.stringify(draftData.assessmentResults[key]));
          } else {
            assessmentResults[key] = draftData.assessmentResults[key];
          }
        });
        console.log("✅ 恢复评估结果完成:", JSON.parse(JSON.stringify(assessmentResults)));
      } else {
        console.warn("⚠️ 草稿数据中没有assessmentResults");
      }
      
      console.log("🎉 评估草稿数据加载并恢复成功！");
      // 🔥 记录草稿恢复时间（相当于最后一次保存时间）
      lastAutoSaveTime.value = new Date();
    } else {
      console.warn("⚠️ 未找到评估草稿数据");
      console.warn("⚠️ 可能原因：");
      console.warn("   1. 数据库中 assessment_draft_json 字段为 NULL");
      console.warn("   2. 第二步评估数据从未被保存过");
      console.warn("   3. SQL查询没有包含 assessment_draft_json 字段");
      console.warn("   4. localStorage 中也没有备份数据");
      
      // 如果是审批模式且没有评估数据，给出警告
      if (isApprovalMode.value) {
        console.error("🚨 严重问题：审批模式下缺少评估数据！");
        console.error("   入住管理ID:", checkInManagementId);
        console.error("   建议：请联系申请人完成第二步评估后再进行审批");
      }
    }
  } catch (error) {
    console.error("❌ 加载评估草稿数据失败:", error);
    console.error("❌ 错误堆栈:", error.stack);
    // 不抛出错误，允许流程继续
  } finally {
    // 🔥【关键修复】恢复完成后，重置标志位
    // 使用 nextTick 确保所有响应式更新都已完成
    await nextTick();
    isRestoringDraft.value = false;
    console.log("🔓 草稿数据恢复完成，已解除watch限制");
    console.log("🔓 最终healthForm状态:", JSON.parse(JSON.stringify(healthForm)));
    console.log("🔓 最终abilityForm状态:", JSON.parse(JSON.stringify(abilityForm)));
    console.log("🔓 最终assessmentResults状态:", JSON.parse(JSON.stringify(assessmentResults)));
  }
};

/**
 * 🔥【新增】监听评估数据变化，自动保存草稿
 */
let autoSaveTimer = null;
const setupAutoSaveWatcher = () => {
  // 🔥【关键修复】Vue3监听reactive对象需要直接传递对象，不需要箭头函数
  watch(healthForm, (newVal, oldVal) => {
    if (isRestoringDraft.value) {
      console.log("⏸️ 正在恢复草稿数据，跳过自动保存");
      return;
    }
    
    // 只有在第二步时才自动保存
    if (currentStep.value !== 2) {
      console.log("⏸️ 不在第二步，跳过自动保存");
      return;
    }
    
    console.log("📝 healthForm数据变化，准备自动保存...");
    triggerAutoSave();
  }, { deep: true });
  
  // 监听abilityForm变化
  watch(abilityForm, (newVal, oldVal) => {
    if (isRestoringDraft.value) {
      console.log("⏸️ 正在恢复草稿数据，跳过自动保存");
      return;
    }
    
    if (currentStep.value !== 2) {
      console.log("⏸️ 不在第二步，跳过自动保存");
      return;
    }
    
    console.log("📝 abilityForm数据变化，准备自动保存...");
    triggerAutoSave();
  }, { deep: true });
  
  // 监听assessmentResults变化
  watch(assessmentResults, (newVal, oldVal) => {
    if (isRestoringDraft.value) {
      console.log("⏸️ 正在恢复草稿数据，跳过自动保存");
      return;
    }
    
    if (currentStep.value !== 2) {
      console.log("⏸️ 不在第二步，跳过自动保存");
      return;
    }
    
    console.log("📝 assessmentResults数据变化，准备自动保存...");
    triggerAutoSave();
  }, { deep: true });
  
  console.log("✅ 已设置3个watch监听器：healthForm、abilityForm、assessmentResults");
};

/**
 * 触发自动保存（防抖处理，1秒后保存）
 */
const triggerAutoSave = () => {
  // 清除之前的定时器
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer);
  }
  
  // 设置新的定时器（1秒后保存，快速响应用户输入）
  autoSaveTimer = setTimeout(async () => {
    console.log("⏰ 触发自动保存...");
    await autoSaveAssessmentData();
  }, 1000);
};

/**
 * 添加家属成员
 */
const addFamilyMember = () => {
  familyForm.members.push({ name: "", contact: "", relationship: "" });
};

/**
 * 删除家属成员
 * @param {Number} index - 要删除的索引
 */
const removeFamilyMember = (index) => {
  if (familyForm.members.length > 1) {
    familyForm.members.splice(index, 1);
  }
};

// 添加用药记录
const addMedication = () => {
  healthForm.medications.push({ name: "", method: "", dosage: "" });
};

// 删除用药记录
const removeMedication = (index) => {
  if (healthForm.medications.length > 1) {
    healthForm.medications.splice(index, 1);
  }
};

// ==================== 一寸照片上传处理 ====================
/**
 * 处理一寸照片文件上传
 * @param {Object} file - 上传的文件对象
 * @returns {boolean} - 上传是否成功
 */
const handlePhotoUpload = (file) => {
  try {
    // 验证文件格式和大小
    checkUpload([file], "一寸照片");
    // 替换旧文件，只保留最新上传的文件
    photoFiles.value = [file];
    
    return true;
  } catch (error) {
    console.error("一寸照片上传失败:", error.message);
    ElMessage.error(error.message);
    return false;
  }
};

/**
 * 删除一寸照片
 */
const handlePhotoRemove = () => {
  
  photoFiles.value = [];
};

// ==================== 身份证人像面上传处理 ====================
/**
 * 处理身份证人像面文件上传
 * @param {Object} file - 上传的文件对象
 * @returns {boolean} - 上传是否成功
 */
const handleIdCardFrontUpload = (file) => {
  try {
    // 验证文件格式和大小
    checkUpload([file], "身份证人像面");
    // 替换旧文件，只保留最新上传的文件
    idCardFrontFiles.value = [file];
    
    return true;
  } catch (error) {
    console.error("身份证人像面上传失败:", error.message);
    ElMessage.error(error.message);
    return false;
  }
};

/**
 * 删除身份证人像面
 */
const handleIdCardFrontRemove = () => {
  
  idCardFrontFiles.value = [];
};

// ==================== 身份证国徽面上传处理 ====================
/**
 * 处理身份证国徽面文件上传
 * @param {Object} file - 上传的文件对象
 * @returns {boolean} - 上传是否成功
 */
const handleIdCardBackUpload = (file) => {
  try {
    // 验证文件格式和大小
    checkUpload([file], "身份证国徽面");
    // 替换旧文件，只保留最新上传的文件
    idCardBackFiles.value = [file];
    
    return true;
  } catch (error) {
    console.error("身份证国徽面上传失败:", error.message);
    ElMessage.error(error.message);
    return false;
  }
};

/**
 * 删除身份证国徽面
 */
const handleIdCardBackRemove = () => {
  
  idCardBackFiles.value = [];
};

// ==================== 文件上传到服务器 ====================
/**
 * 上传文件到服务器
 * @param {File} file - 要上传的文件对象
 * @param {string} fileLabel - 文件标签（用于错误提示）
 * @returns {Promise<string>} - 返回上传后的文件URL
 */
const uploadFileToServer = async (file, fileLabel = '文件') => {
  try {
    if (!file) {
      throw new Error(`${fileLabel}文件不存在`);
    }

    // 创建FormData对象
    const formData = new FormData();
    formData.append('file', file);

    // 获取上传URL和认证头
    const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/common/upload';
    const headers = {
      'Authorization': 'Bearer ' + getToken(),
      'Content-Type': 'multipart/form-data'
    };

    console.log(`开始上传${fileLabel}到服务器:`, uploadUrl);

    // 发送上传请求
    const response = await axios.post(uploadUrl, formData, { headers });

    console.log(`${fileLabel}上传响应:`, response.data);

    // 检查响应状态
    if (response.data && response.data.code === 200) {
      // 获取文件URL
      const fileUrl = response.data.fileName || response.data.url;
      if (!fileUrl) {
        throw new Error(`${fileLabel}上传成功但未返回文件URL`);
      }
      return fileUrl;
    } else {
      throw new Error(response.data?.msg || `${fileLabel}上传失败`);
    }
  } catch (error) {
    console.error(`${fileLabel}上传失败:`, error);
    throw new Error(`${fileLabel}上传失败: ${error.message || '未知错误'}`);
  }
};

// ==================== 文件处理辅助函数 ====================
/**
 * 从文件URL中提取文件名
 * @param {string} url - 文件URL
 * @param {string} defaultName - 默认文件名
 * @returns {string} - 提取的文件名
 */
const extractFileNameFromUrl = (url, defaultName) => {
  if (!url) return defaultName;
  
  try {
    // 从URL中提取文件名
    const fileName = url.split('/').pop();
    // 如果提取成功且不为空，则使用提取的文件名
    if (fileName && fileName.includes('.')) {
      return fileName;
    }
    // 否则使用默认文件名
    return defaultName;
  } catch (error) {
    console.warn("提取文件名失败:", error);
    return defaultName;
  }
};

// ==================== 文件预览函数 ====================
/**
 * 通过fetch获取数据库文件并转换为可预览的URL
 * @param {string} fileUrl - 数据库中的文件URL
 * @returns {Promise<string>} - 可预览的Blob URL
 */
const fetchDatabaseFile = async (fileUrl) => {
  try {
    
    // 尝试获取文件
    const response = await fetch(fileUrl, {
      method: 'GET',
      headers: {
        'Accept': 'image/*,application/pdf,*/*',
      },
      mode: 'cors', // 允许跨域
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    // 获取文件数据
    const blob = await response.blob();
    
    // 创建可预览的URL
    const blobUrl = URL.createObjectURL(blob);
    
    return blobUrl;
  } catch (error) {
    console.error("获取数据库文件失败:", error);
    throw new Error(`无法获取文件: ${error.message}`);
  }
};

/**
 * 文件预览处理函数
 * 支持预览数据库中的文件（有url属性）和新上传的文件（有raw属性）
 * @param {Object} file - 文件对象，包含name、url或raw属性
 */
const previewFile = (file) => {
  try {
    let fileUrl;
    let needCleanup = false; // 标记是否需要清理URL对象
    
    // 判断文件来源：数据库文件（有url属性）还是新上传文件（有raw属性）
    if (file.url) {
      // 从数据库获取的文件，直接使用URL
      
      // 检查URL是否有效
      if (!file.url || file.url.toString().trim() === '') {
        throw new Error("文件URL为空，无法预览");
      }
      
      // 直接使用数据库中的完整路径，确保以 /profile/ 开头
      if (file.url.startsWith('/profile/')) {
        fileUrl = file.url;
      } else {
        fileUrl = '/profile' + file.url;
      }
      
      
      needCleanup = false; // 数据库URL不需要清理
      
    } else if (file.raw) {
      // 新上传的文件，创建临时URL
      fileUrl = URL.createObjectURL(file.raw);
      needCleanup = true; // 需要清理临时URL
    } else {
      throw new Error("文件数据不完整，无法预览");
    }

    const newWindow = window.open("", "_blank");

    if (newWindow) {
      // 判断文件类型
      const isPdf = file.name.toLowerCase().endsWith(".pdf");

      if (isPdf) {
        // PDF文件预览
        newWindow.document.write(`
          <html>
            <head>
              <title>${file.name}</title>
              <style>
                body { margin: 0; padding: 0; height: 100vh; background-color: #f0f2f5; }
                .container { height: 100vh; display: flex; flex-direction: column; }
                .title { padding: 10px 20px; background-color: #fff; border-bottom: 1px solid #dcdfe6; }
                .pdf-container { flex: 1; overflow: hidden; }
                iframe { width: 100%; height: 100%; border: none; }
              </style>
            </head>
            <body>
              <div class="container">
                <div class="title">${file.name}</div>
                <div class="pdf-container">
                  <iframe src="${fileUrl}" type="application/pdf"></iframe>
                </div>
              </div>
            </body>
          </html>
        `);
      } else {
        // 图片文件预览
        newWindow.document.write(`
          <html>
            <head>
              <title>${file.name}</title>
              <style>
                body { margin: 0; padding: 20px; background-color: #f0f2f5; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
                .container { text-align: center; max-width: 90vw; }
                .title { margin-bottom: 20px; font-size: 18px; color: #303133; font-weight: 500; }
                img { max-width: 100%; max-height: 80vh; border: 1px solid #dcdfe6; box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15); border-radius: 4px; }
                .error { color: #f56c6c; margin-top: 20px; padding: 20px; background: #fef0f0; border: 1px solid #fbc4c4; border-radius: 4px; }
                .loading { color: #409eff; margin-top: 20px; }
                .btn { margin-top: 15px; padding: 8px 16px; background: #409eff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; }
                .btn:hover { background: #66b1ff; }
              </style>
            </head>
            <body>
              <div class="container">
                <div class="title">${file.name}</div>
                <img src="${fileUrl}" alt="${file.name}" 
                     onerror="document.getElementById('loading').style.display='none';document.getElementById('error').style.display='block';"
                     onload="document.getElementById('loading').style.display='none';">
                <div class="loading" id="loading">正在加载图片...</div>
                <div class="error" id="error" style="display: none;">
                  图片加载失败，可能是文件不存在或无法访问。<br>
                  文件URL: ${fileUrl}<br>
                  <button class="btn" onclick="window.open('${fileUrl}', '_blank')">在新标签页中打开</button>
              </div>
              </div>
              <!-- 移除内联 script，避免与外层 SFC 的 <script> 冲突 -->
            </body>
          </html>
        `);
      }

      newWindow.document.close();
      
      // 只有临时URL才需要清理，避免内存泄漏
      if (needCleanup) {
      newWindow.onbeforeunload = () => {
        URL.revokeObjectURL(fileUrl);
      };
      }
    } else {
      ElMessage.warning("无法打开预览窗口，请检查浏览器设置");
    }
  } catch (error) {
    ElMessage.error("预览文件失败：" + error.message);
  }
};
// 体检报告上传处理
const handleMedicalReportUpload = (file) => {
  medicalReportFiles.value = [file];
};

// 体检报告删除处理
const handleMedicalReportRemove = (file) => {
  // 找到文件在数组中的索引
  const index = medicalReportFiles.value.findIndex(
    (item) => item.uid === file.uid
  );
  if (index > -1) {
    // 移除指定的文件
    medicalReportFiles.value.splice(index, 1);
  }
};

// 获取提交按钮文本
const getSubmitButtonText = () => {
  switch (currentStep.value) {
    case 1:
      return "提交";
    case 2:
      return "提交评估";
    case 3:
      if (!canApprove.value) {
        return "等待审批";
      }
      return approvalState.showResult ? "确认审批" : "提交审批";
    case 4:
      return "提交配置";
    case 5:
      return "完成签约";
    default:
      return "提交";
  }
};

// 验证当前标签页的表单数据
const validateCurrentTabForm = async (tabIndex) => {
  switch (tabIndex) {
    case 1: // 基本信息
      await basicFormRef.value.validate();
      // 额外验证身份证和手机号
      if (!/^[\u4e00-\u9fa5]{2,10}$/.test(basicForm.name)) {
        throw new Error("请输入2-10个中文字符的姓名");
      }
      if (!/^\d{17}[\dXx]$/.test(basicForm.idCard)) {
        throw new Error("请输入有效的18位身份证号码");
      }
      if (!/^1[3-9]\d{9}$/.test(basicForm.contact)) {
        throw new Error("请输入有效的手机号码");
      }
      break;

    case 2: // 家属信息 - 按照图片规则严格验证
      // 1. 检查是否有家属信息
      if (familyForm.members.length === 0) {
        throw new Error("家属信息不完整，请输入家属信息");
      }

      // 2. 验证每个家属信息的完整性
      for (let i = 0; i < familyForm.members.length; i++) {
        const member = familyForm.members[i];

        // 家属姓名验证（必填，10个字符）
        if (!member.name || member.name.toString().trim() === "") {
          throw new Error("家属信息不完整，请输入家属信息");
        }
        if (!/^[\u4e00-\u9fa5]{2,10}$/.test(member.name)) {
          throw new Error("家属姓名必须是2-10个中文字符");
        }

        // 家属联系方式验证（必填，11位手机号格式）
        if (!member.contact || member.contact.toString().trim() === "") {
          throw new Error("家属信息不完整，请输入家属信息");
        }
        if (!/^1[3-9]\d{9}$/.test(member.contact)) {
          throw new Error("手机号格式错误，请重新输入");
        }

        // 与老人关系验证（必填）
        if (!member.relationship) {
          throw new Error("家属信息不完整，请输入家属信息");
        }
      }
      break;

    case 3: // 资料上传页验证
      try {
        // 验证三张必传图片
        checkUpload(photoFiles.value, "一寸照片");
        checkUpload(idCardFrontFiles.value, "身份证人像面");
        checkUpload(idCardBackFiles.value, "身份证国徽面");
      } catch (error) {
        console.error("文件验证失败:", error);
        throw error; // 重新抛出错误以便外层捕获
      }
      break;

    case 4: // 健康评估
      if (healthForm.diseases.length === 0) {
        throw new Error("请填写疾病诊断信息");
      }
      break;

    case 5: // 能力评估
      if (
        !abilityForm.eating ||
        !abilityForm.bathing ||
        !abilityForm.grooming
      ) {
        throw new Error("请完成所有能力评估项目");
      }
      break;

    case 6: // 评估报告
      if (!assessmentResults.finalLevel) {
        throw new Error("请确定最终能力等级");
      }
      break;
  }
};

// 提交处理
const handleSubmit = async () => {
  try {
    // 第一步：申请入住步骤（包含3个标签页）
    if (currentStep.value === 1) {
      // 检查权限
      if (!canEditCurrentStep(1)) {
        ElMessage.warning("您没有权限编辑申请入住信息");
        return;
      }
      
      // 先验证当前标签页
      await validateCurrentTabForm(currentApplyTab.value);

      

      // 如果是资料上传页（第3个标签页）
      if (currentApplyTab.value === 3) {
        

        // 简单验证三个图片是否已上传
        if (!photoFiles.value || photoFiles.value.length === 0) {
          throw new Error("请上传一寸照片");
        }
        if (!idCardFrontFiles.value || idCardFrontFiles.value.length === 0) {
          throw new Error("请上传身份证人像面照片");
        }
        if (!idCardBackFiles.value || idCardBackFiles.value.length === 0) {
          throw new Error("请上传身份证国徽面照片");
        }

        // 只有资料上传验证通过才执行这里

        // 🔥【关键】先上传三个图片文件到服务器（如果有的话）
        let photoUrl = '';
        let idCardFrontUrl = '';
        let idCardBackUrl = '';
        
        try {
          // 只有当文件存在时才上传
          if (photoFiles.value && photoFiles.value.length > 0 && photoFiles.value[0].raw) {
            ElMessage.info('正在上传一寸照片...');
            photoUrl = await uploadFileToServer(photoFiles.value[0].raw, '一寸照片');
            console.log('一寸照片上传成功:', photoUrl);
          }
          
          if (idCardFrontFiles.value && idCardFrontFiles.value.length > 0 && idCardFrontFiles.value[0].raw) {
            ElMessage.info('正在上传身份证人像面...');
            idCardFrontUrl = await uploadFileToServer(idCardFrontFiles.value[0].raw, '身份证人像面');
            console.log('身份证人像面上传成功:', idCardFrontUrl);
          }
          
          if (idCardBackFiles.value && idCardBackFiles.value.length > 0 && idCardBackFiles.value[0].raw) {
            ElMessage.info('正在上传身份证国徽面...');
            idCardBackUrl = await uploadFileToServer(idCardBackFiles.value[0].raw, '身份证国徽面');
            console.log('身份证国徽面上传成功:', idCardBackUrl);
          }
          
          if (photoUrl || idCardFrontUrl || idCardBackUrl) {
            ElMessage.success('图片上传成功');
          }
          
        } catch (uploadError) {
          console.error('图片上传失败:', uploadError);
          ElMessage.warning('图片上传失败，但将继续提交其他数据: ' + (uploadError.message || '未知错误'));
          // 不return，继续提交其他数据
        }

        // 验证通过，启动工作流
        try {
          // 🔥【关键】字典值转换 - 将显示标签转换为数据库ID
          console.log('🔍 开始字典值转换...');
          const ethnicityValue = getDictValue(dictData.nationList, basicForm.ethnicity);
          const religionValue = getDictValue(dictData.religionList, basicForm.religion);
          const hobbiesValue = getDictValue(dictData.hobbyList, basicForm.hobbies);
          
          console.log('民族转换:', basicForm.ethnicity, '->', ethnicityValue);
          console.log('宗教转换:', basicForm.religion, '->', religionValue);
          console.log('爱好转换:', basicForm.hobbies, '->', hobbiesValue);
          
          // 民族是必填项，如果为空则阻止提交
          if (!ethnicityValue) {
            ElMessage.error('民族是必填项，请选择民族');
            return;
          }
          
          // 🔥【关键】构建完整的申请数据（参考404项目）
          const applicationData = {
            // ===== 基本信息 =====
            name: basicForm.name,
            idCard: basicForm.idCard,
            contact: basicForm.contact,
            address: basicForm.address,
            photo: photoUrl,
            idCardFront: idCardFrontUrl,
            idCardBack: idCardBackUrl,
            
            // ===== 老人详细信息（字典字段 - 需要转换为字典值ID） =====
            gender: basicForm.gender,
            birthDate: basicForm.birthDate,
            age: basicForm.age,
            ethnicity: ethnicityValue, // 🔥 转换后的民族ID
            politicalStatus: getDictValue(dictData.politicalList, basicForm.politicalStatus),
            religion: religionValue, // 🔥 转换后的宗教ID
            maritalStatus: getDictValue(dictData.maritalList, basicForm.maritalStatus),
            education: getDictValue(dictData.educationList, basicForm.education),
            incomeSource: getDictValue(dictData.incomeList, basicForm.incomeSource),
            hobbies: hobbiesValue, // 🔥 转换后的爱好ID
            medicalInsurance: getDictValue(dictData.medicalList, basicForm.medicalInsurance),
            medicalCardNo: basicForm.medicalCardNo,
            
            // ===== 家属信息列表（过滤掉空记录） =====
            familyMembers: familyForm.members.filter(member => 
              member.name && member.name.trim() !== ''
            ),
            
            // ===== 评估信息（护理等级代码） =====
            nursingLevelCode: assessmentResults.finalLevel || assessmentResults.nursingLevel,
            
            // ===== 配置信息 =====
            bedId: configForm.bedId,
            checkInStartTime: configForm.checkInStartTime,
            checkInEndTime: configForm.checkInEndTime,
            deposit: configForm.deposit,
            nursingFee: configForm.nursingFee,
            bedFee: configForm.bedFee,
            otherFee: configForm.otherFee,
            
            // ===== 合同信息 =====
            contractNo: contractForm.contractNo,
            contractName: contractForm.contractName,
            contractStartDate: contractForm.contractStartDate,
            contractEndDate: contractForm.contractEndDate,
            signDate: contractForm.signDate,
            partyCName: contractForm.partyCName,
            partyCPhone: contractForm.partyCPhone,
            contractFile: contractFiles.value[0]?.url || ''
          };
          
          console.log('========== 📝 最终提交的数据 ==========');
          console.log('完整applicationData:', JSON.stringify(applicationData, null, 2));
          console.log('ethnicity:', applicationData.ethnicity);
          console.log('religion:', applicationData.religion);
          console.log('hobbies:', applicationData.hobbies);
          console.log('familyMembers数量:', applicationData.familyMembers?.length);
          console.log('====================================');
          
          // 提交完整申请
          const response = await completeApplication(applicationData);
          if (response.code === 200) {
            ElMessage.success("入住申请提交成功，工作流已启动");
            workflowStarted.value = true;
            
            // 启动工作流
            const workflowResponse = await startWorkflow(response.id);
            if (workflowResponse.code === 200) {
              processInstanceId.value = workflowResponse.processInstanceId;
              workflowStatus.value = '进行中';
              ElMessage.success("工作流启动成功");
            }
            
            // 🔥【修改】提交成功后不跳转到第二步，询问用户是否返回管理页面
            ElMessageBox.confirm(
              "入住申请已提交成功！下一步需要护理员组长进行评估。是否返回入住管理页面？",
              "提交成功",
              {
                type: "success",
                confirmButtonText: "返回管理页面",
                cancelButtonText: "留在当前页"
              }
            ).then(() => {
              // 用户选择返回管理页面
              router.push('/Exit/mm2/management');
            }).catch(() => {
              // 用户选择留在当前页，提示已提交
              ElMessage.info("您的申请已提交，等待下一步审批");
            });
            return;
          } else {
            throw new Error(response.msg || "申请提交失败");
          }
        } catch (error) {
          console.error("启动工作流失败:", error);
          ElMessage.error("启动工作流失败: " + error.message);
          return;
        }
      }

      // 如果不是最后一个标签页，跳转到下一个标签页
      currentApplyTab.value++;
      return;
    }

    // 第二步：入住评估步骤（包含3个标签页）
    if (currentStep.value === 2) {
      // 检查权限
      if (!canEditCurrentStep(2)) {
        ElMessage.warning("您没有权限编辑入住评估信息");
        return;
      }
      
      if (currentAssessmentTab.value < assessmentTabs.value.length) {
        await validateCurrentTabForm(currentAssessmentTab.value + 3); // +3 因为前面有3个申请标签页
        currentAssessmentTab.value++;
        return;
      }
      await validateCurrentTabForm(currentAssessmentTab.value + 3);

      // 🔥【修改】完成评估后保存数据并提交任务
      try {
        const taskId = route.query.taskId;
        const businessId = route.query.id;
        if (taskId && businessId) {
          // 🔥【关键修复】将完整的评估数据保存为JSON格式
          const assessmentData = {
            // 健康评估数据（保存所有字段）
            healthForm: JSON.parse(JSON.stringify(healthForm)),
            // 能力评估数据（保存所有字段）
            abilityForm: JSON.parse(JSON.stringify(abilityForm)),
            // 评估结果（保存所有字段）
            assessmentResults: JSON.parse(JSON.stringify(assessmentResults)),
          };

          console.log("📝 保存评估数据:", assessmentData);
          
          // 调用保存评估草稿API
          try {
            await saveAssessmentDraft(businessId, JSON.stringify(assessmentData));
            console.log("✅ 评估数据保存成功");
          } catch (saveError) {
            console.warn("⚠️ 评估数据保存失败:", saveError);
            // 即使保存失败，也继续提交任务
          }
          
          // 🔥 第二步：提交工作流任务
          await handleTask(taskId, "评估完成", 1, businessId, currentStep.value);
          
          // 🔥 清除未保存标记，避免路由守卫拦截
          hasUnsavedChanges.value = false;
          
          // 🔥 提交成功后，直接返回待办列表
          ElMessage.success("入住评估已提交成功！下一步需要副院长进行审批。");
          router.push('/xtgz/xtgz/tasks');
        } else {
          ElMessage.error("缺少任务信息，无法提交");
        }
      } catch (error) {
        console.error("提交评估失败:", error);
        ElMessage.error("提交评估失败: " + error.message);
      }
      return;
    }

    // 第三步：入住审批步骤
    if (currentStep.value === 3) {
      // 检查权限
      if (!canEditCurrentStep(3)) {
        ElMessage.warning("您没有权限进行入住审批");
        return;
      }
      
      if (!approvalState.showResult) {
        // 只有副院长可以审批
        if (!canApprove.value) {
          ElMessage.warning("您没有审批权限，请联系副院长处理");
          return;
        }
        
        // 管理员第一次点击提交审批，显示审批结果
        approvalState.showResult = true;
        // 模拟审批结果和意见
        approvalState.approvalResult = "审批通过";
        approvalState.approvalComment = "符合入住条件，同意入住";
        ElMessage.success("审批结果已显示");
        return;
      } else {
        // 只有管理员且审批通过才能进入下一步
        if (!canApprove.value) {
          ElMessage.warning("您没有权限继续操作");
          return;
        }
        
        if (approvalState.approvalResult !== "审批通过") {
          ElMessage.warning("只有审批通过才能继续下一步");
          return;
        }
        
        // 提交审批结果到后端
        try {
          const taskId = route.query.taskId;
          const businessId = route.query.id;
          if (taskId && businessId) {
            const auditStatus = approvalState.approvalResult === "审批通过" ? 1 : 2;
            // 修复参数传递：API函数期望5个独立参数（包括stepNo）
            await handleTask(taskId, approvalState.approvalComment, auditStatus, businessId, currentStep.value);
            
            // 🔥 清除未保存标记，避免路由守卫拦截
            hasUnsavedChanges.value = false;
            
            // 🔥 提交成功后，直接返回待办列表
            ElMessage.success("入住审批已提交成功！下一步需要养老顾问进行配置。");
            router.push('/xtgz/xtgz/tasks');
          }
        } catch (error) {
          console.error("审批提交失败:", error);
          ElMessage.error("审批提交失败: " + error.message);
          return;
        }
        
        return;
      }
    }

    // 第四步：入住配置步骤
    if (currentStep.value === 4) {
      // 检查权限
      if (!canEditCurrentStep(4)) {
        ElMessage.warning("您没有权限编辑入住配置信息");
        return;
      }
      
      // 配置步骤校验
      if (configFormRef.value && configFormRef.value.validate) {
        await configFormRef.value.validate();
      }
      
      // 🔥【修改】配置完成后保存数据并提交任务
      try {
        const taskId = route.query.taskId;
        const businessId = route.query.id;
        if (taskId && businessId) {
          // 🔥 第一步：构建配置数据
          const configData = {
            checkInManagementId: businessId,
            // 床位信息
            bedId: configForm.bedId,
            floorId: configForm.floorId,
            roomId: configForm.roomId,
            bedNo: configForm.bedNo,
            // 入住期限
            checkInStartTime: configForm.stayPeriod && configForm.stayPeriod.length > 0 
              ? normalizeToYMD(configForm.stayPeriod[0]) 
              : '',
            checkInEndTime: configForm.stayPeriod && configForm.stayPeriod.length > 1 
              ? normalizeToYMD(configForm.stayPeriod[1]) 
              : '',
            // 费用期限
            feeStartDate: configForm.feePeriod && configForm.feePeriod.length > 0 
              ? normalizeToYMD(configForm.feePeriod[0]) 
              : '',
            feeEndDate: configForm.feePeriod && configForm.feePeriod.length > 1 
              ? normalizeToYMD(configForm.feePeriod[1]) 
              : '',
            // 护理等级
            nursingLevelId: configForm.nursingLevel,
            planId: configForm.planId,
            // 费用信息
            deposit: configForm.deposit,
            nursingFee: configForm.nursingFee,
            bedFee: configForm.bedFee,
            otherFee: configForm.otherFee,
            medicalInsurancePayment: configForm.insurancePayment,
            governmentSubsidy: configForm.governmentSubsidy,
          };

          console.log("📝 保存配置数据:", configData);
          
          // 调用配置入住API
          try {
            await configureCheckIn(configData);
            console.log("✅ 配置数据保存成功");
          } catch (saveError) {
            console.warn("⚠️ 配置数据保存失败:", saveError);
            // 即使保存失败，也继续提交任务
          }
          
          // 🔥 第二步：提交工作流任务
          await handleTask(taskId, "配置完成", 1, businessId, currentStep.value);
          
          // 🔥 清除未保存标记，避免路由守卫拦截
          hasUnsavedChanges.value = false;
          
          // 🔥 提交成功后，直接返回待办列表
          ElMessage.success("入住配置已提交成功！下一步需要法务部员工进行签约办理。");
          router.push('/xtgz/xtgz/tasks');
        } else {
          ElMessage.error("缺少任务信息，无法提交");
        }
      } catch (error) {
        console.error("提交配置失败:", error);
        ElMessage.error("提交配置失败: " + error.message);
      }
      return;
    }

    if (currentStep.value === 5) {
      // 检查权限
      if (!canEditCurrentStep(5)) {
        ElMessage.warning("您没有权限进行签约办理");
        return;
      }
      
      // 签约办理步骤校验
      if (contractFormRef.value && contractFormRef.value.validate) {
        await contractFormRef.value.validate();
      }
      
      // 🔥【修改】签约完成后保存数据并提交任务
      try {
        const taskId = route.query.taskId;
        const businessId = route.query.id;
        if (taskId && businessId) {
          // 🔥 第一步：构建签约数据
          const signData = {
            checkInManagementId: businessId,
            // 合同信息
            contractNo: contractForm.contractNumber,
            contractName: contractForm.contractName,
            contractStartDate: contractForm.contractStartTime 
              ? normalizeToYMD(contractForm.contractStartTime) 
              : '',
            contractEndDate: contractForm.contractEndTime 
              ? normalizeToYMD(contractForm.contractEndTime) 
              : '',
            signDate: contractForm.signDate 
              ? normalizeToYMD(contractForm.signDate) 
              : '',
            partyCName: contractForm.partyCName,
            partyCPhone: contractForm.partyCcontact,
            contractFile: contractFiles.value && contractFiles.value.length > 0 
              ? contractFiles.value[0].url 
              : '',
          };

          console.log("📝 保存签约数据:", signData);
          
          // 调用签约办理API
          try {
            await signContract(signData);
            console.log("✅ 签约数据保存成功");
          } catch (saveError) {
            console.warn("⚠️ 签约数据保存失败:", saveError);
            // 即使保存失败，也继续提交任务
          }
          
          // 🔥 第二步：提交工作流任务
          await handleTask(taskId, "签约办理完成", 1, businessId, currentStep.value);
          
          // 🔥 清除未保存标记，避免路由守卫拦截
          hasUnsavedChanges.value = false;
          
          // 🔥 所有步骤完成，直接返回待办列表
          ElMessage.success("入住申请流程已完成！所有步骤均已完成。");
          router.push('/xtgz/xtgz/tasks');
        } else {
          ElMessage.error("缺少任务信息，无法提交");
        }
      } catch (error) {
        console.error("提交签约失败:", error);
        ElMessage.error("提交签约失败: " + error.message);
      }
      return;
    }

  } catch (error) {
    console.error("提交出错:", error);
    ElMessage.error(error.message || "请完成当前步骤的所有必填内容");
  }
};

// 返回入住管理列表
const handleReturnToList = () => {
  // 🔥 直接返回，不再检查未保存数据
  router.push('/Exit/mm2/management');
  
  // if (hasUnsavedChanges.value) {
  //   ElMessageBox.confirm(
  //     "当前有未保存的数据，确定要返回入住管理列表吗？",
  //     "未保存提示",
  //     { type: "warning", confirmButtonText: "确定", cancelButtonText: "取消" }
  //   )
  //     .then(() => {
  //       hasUnsavedChanges.value = false;
  //       router.push('/Exit/mm2/management');
  //     })
  //     .catch(() => {});
  // } else {
  //   router.push('/Exit/mm2/management');
  // }
};

// 取消并确认
const handleCancel = () => {
  ElMessageBox.confirm(
    "确定要取消并返回入住管理列表吗？",
    "确认取消",
    { type: "warning", confirmButtonText: "确定", cancelButtonText: "继续编辑" }
  )
    .then(() => {
      hasUnsavedChanges.value = false;
      router.push('/Exit/mm2/management');
    })
    .catch(() => {});
};


// ==================== 表单权限控制函数 ====================
/**
 * 根据当前步骤和用户角色获取表单字段权限
 * @param {number} step - 当前步骤
 * @param {string} fieldName - 字段名称
 * @returns {object} - 权限对象 {editable: boolean, visible: boolean}
 */
const getFormPermissions = (step, fieldName) => {
  const permissions = {
    // 养老顾问权限
    'rzyanglaoguwen': {
      1: { editable: true, visible: true },   // 申请入住 - 可编辑
      2: { editable: false, visible: true },  // 入住评估 - 只读
      3: { editable: false, visible: true },  // 入住审批 - 只读
      4: { editable: true, visible: true },  // 入住配置 - 可编辑
      5: { editable: false, visible: true }   // 签约办理 - 只读
    },
    // 护理组部长权限
    'rzhuliyuanzuzhang': {
      1: { editable: false, visible: true },  // 申请入住 - 只读
      2: { editable: true, visible: true },   // 入住评估 - 可编辑
      3: { editable: false, visible: true },  // 入住审批 - 只读
      4: { editable: false, visible: true },  // 入住配置 - 只读
      5: { editable: false, visible: true }   // 签约办理 - 只读
    },
    // 副院长权限
    'rzfuyuanzhang': {
      1: { editable: false, visible: true },  // 申请入住 - 只读
      2: { editable: false, visible: true },  // 入住评估 - 只读
      3: { editable: true, visible: true },  // 入住审批 - 可编辑
      4: { editable: false, visible: true },  // 入住配置 - 只读
      5: { editable: false, visible: true }   // 签约办理 - 只读
    },
    // 法务部员工权限
    'rzfawubuyuangong': {
      1: { editable: false, visible: true },  // 申请入住 - 只读
      2: { editable: false, visible: true },  // 入住评估 - 只读
      3: { editable: false, visible: true },  // 入住审批 - 只读
      4: { editable: false, visible: true },  // 入住配置 - 只读
      5: { editable: true, visible: true }    // 签约办理 - 可编辑
    }
  };
  
  // 获取当前用户角色
  const userRole = userStore.roles.find(role => 
    ['rzyanglaoguwen', 'rzhuliyuanzuzhang', 'rzfuyuanzhang', 'rzfawubuyuangong'].includes(role)
  );
  
  if (!userRole || !permissions[userRole] || !permissions[userRole][step]) {
    return { editable: false, visible: false };
  }
  
  return permissions[userRole][step];
};

/**
 * 🔥【修改】检查当前用户是否有权限编辑当前步骤
 * @param {number} step - 当前步骤
 * @returns {boolean} - 是否有编辑权限
 */
const canEditCurrentStep = (step) => {
  // 🔥【修改】查看模式下，所有步骤都不可编辑
  if (isViewMode.value) {
    return false;
  }
  
  // 🔥【新增】审批模式下，只有当前用户负责的步骤可编辑，历史步骤只读
  if (isApprovalMode.value) {
    const currentUserStep = getCurrentUserStep();
    // 只有当前步骤等于用户负责的步骤时，才可编辑
    if (step !== currentUserStep) {
      return false;
    }
  }
  
  const permission = getFormPermissions(step, '');
  return permission.editable;
};

/**
 * 检查当前用户是否有权限查看当前步骤
 * @param {number} step - 当前步骤
 * @returns {boolean} - 是否有查看权限
 */
const canViewCurrentStep = (step) => {
  const permission = getFormPermissions(step, '');
  return permission.visible;
};

/**
 * 🔥【修改】判断步骤是否应该被禁用
 * @param {number} stepId - 步骤ID
 * @returns {boolean} - 是否禁用
 */
const isStepDisabled = (stepId) => {
  // 查看模式下，只能查看用户处理的步骤及之前的步骤，后续步骤禁用
  if (isViewMode.value) {
    return stepId > maxViewableStep.value;
  }
  
  // 🔥【修改】审批模式下，可以查看当前步骤及之前的步骤（只读），未来步骤禁用
  if (isApprovalMode.value) {
    const currentUserStep = getCurrentUserStep();
    return stepId > currentUserStep;
  }
  
  // 普通模式下，只能访问已完成或当前步骤，后续步骤禁用
  return stepId > currentStep.value;
};

/**
 * 获取当前用户角色名称
 * @returns {string} - 角色名称
 */
const getCurrentUserRoleName = () => {
  const roleMap = {
    'rzyanglaoguwen': '养老顾问',
    'rzhuliyuanzuzhang': '护理组部长',
    'rzfuyuanzhang': '副院长',
    'rzfawubuyuangong': '法务部员工'
  };
  
  const userRole = userStore.roles.find(role => 
    ['rzyanglaoguwen', 'rzhuliyuanzuzhang', 'rzfuyuanzhang', 'rzfawubuyuangong'].includes(role)
  );
  
  return roleMap[userRole] || '未知角色';
};

/**
 * 🔥【新增】获取当前用户应该处理的步骤
 * 根据用户角色返回对应的步骤ID
 * @returns {number} - 步骤ID (1-5)
 */
const getCurrentUserStep = () => {
  // 角色 -> 步骤 映射
  const roleStepMap = {
    'rzyanglaoguwen': 1,      // 养老顾问 -> 步骤1: 申请入住
    'rzhuliyuanzuzhang': 2,    // 护理组部长 -> 步骤2: 入住评估
    'rzfuyuanzhang': 3,        // 副院长 -> 步骤3: 入住审批
    // 'rzyanglaoguwen': 4,    // 养老顾问 -> 步骤4: 入住配置（与步骤1重复，需要通过流程状态判断）
    'rzfawubuyuangong': 5      // 法务部员工 -> 步骤5: 签约办理
  };
  
  const userRole = userStore.roles.find(role => 
    ['rzyanglaoguwen', 'rzhuliyuanzuzhang', 'rzfuyuanzhang', 'rzfawubuyuangong'].includes(role)
  );
  
  // 特殊处理：养老顾问负责步骤1和步骤4，需要根据当前流程进度判断
  if (userRole === 'rzyanglaoguwen') {
    // 如果流程已经到了步骤4，则返回4；否则返回1
    return currentStep.value >= 4 ? 4 : 1;
  }
  
  return roleStepMap[userRole] || currentStep.value;
};

/**
 * 🔥【新增】跳转到当前用户负责的步骤
 * 在审批模式下，如果用户正在查看历史步骤，可以快速跳转到自己负责的步骤
 */
const jumpToMyStep = () => {
  const myStep = getCurrentUserStep();
  if (myStep && myStep !== currentStep.value) {
    currentStep.value = myStep;
    ElMessage.success(`已跳转到第${myStep}步：${getStepTitle(myStep)}`);
  }
};

/**
 * 获取步骤标题
 */
const getStepTitle = (step) => {
  const titles = {
    1: '申请入住',
    2: '入住评估',
    3: '入住审批',
    4: '入住配置',
    5: '签约办理'
  };
  return titles[step] || '';
};

/**
 * 🔥【新增】查看审批记录详情
 * @param {Object} record - 审批记录对象
 */
const viewApprovalRecord = (record) => {
  currentViewingRecord.value = record;
  approvalRecordDialogVisible.value = true;
  console.log("查看审批记录:", record);
};

/**
 * 🔥【新增】从审批记录中打开完整表单查看
 * @param {Object} record - 审批记录对象
 */
const viewFullFormFromRecord = (record) => {
  // 关闭当前弹窗
  approvalRecordDialogVisible.value = false;
  
  // 跳转到对应步骤，使用查看模式
  router.push({
    path: '/system/management/checkInForm',
    query: {
      id: route.query.id,  // 保持业务ID
      mode: 'view',  // 设置为查看模式
      step: record.stepId,  // 跳转到记录对应的步骤
      recordId: record.id  // 可选：记录ID用于后端查询
    }
  });
  
  ElMessage.info(`正在跳转到${record.stepName}步骤查看完整数据...`);
};

/**
 * 🔥【新增】根据步骤ID获取标签类型
 * @param {number} stepId - 步骤ID
 * @returns {string} - Element Plus Tag类型
 */
const getStepTagType = (stepId) => {
  const typeMap = {
    1: '',  // 默认
    2: 'success',
    3: 'warning',
    4: 'danger',
    5: 'info'
  };
  return typeMap[stepId] || '';
};

/**
 * 🔥【新增】保存当前步骤的审批记录
 * 在用户完成审批提交时调用
 */
const saveApprovalRecord = async () => {
  try {
    const newRecord = {
      id: Date.now(),  // 临时ID，实际应该由后端生成
      stepId: currentStep.value,
      stepName: steps[currentStep.value - 1]?.label,
      approver: userStore.user.nickName || userStore.user.userName,
      approverRole: getCurrentUserRoleName(),
      approvalResult: approvalState.approvalResult,
      approvalComment: approvalState.approvalComment,
      approvalTime: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }),
      formData: {
        // 根据当前步骤保存对应的表单数据快照
        step1: currentStep.value === 1 ? {
          basicForm: { ...basicForm },
          familyForm: { ...familyForm },
          photoFiles: photoFiles.value,
          idCardFrontFiles: idCardFrontFiles.value,
          idCardBackFiles: idCardBackFiles.value
        } : null,
        step2: currentStep.value === 2 ? {
          healthForm: { ...healthForm },
          abilityForm: { ...abilityForm },
          assessmentResults: { ...assessmentResults }
        } : null,
        step3: currentStep.value === 3 ? {
          approvalState: { ...approvalState }
        } : null,
        step4: currentStep.value === 4 ? {
          configForm: { ...configForm }
        } : null,
        step5: currentStep.value === 5 ? {
          contractForm: { ...contractForm }
        } : null
      }
    };
    
    // 添加到审批记录列表
    approvalRecords.value.push(newRecord);
    
    // TODO: 调用后端API保存审批记录
    // await saveApprovalRecordToBackend(newRecord);
    
    console.log("✅ 审批记录已保存:", newRecord);
    return newRecord;
  } catch (error) {
    console.error("❌ 保存审批记录失败:", error);
    throw error;
  }
};

/**
 * 🔥【新增】加载审批记录列表
 * 从后端获取该业务的所有审批记录
 */
const loadApprovalRecords = async () => {
  try {
    const managementId = route.query.id;
    if (!managementId) {
      console.log("没有业务ID，跳过加载审批记录");
      return;
    }
    
    // TODO: 调用后端API获取审批记录
    // const response = await getApprovalRecordsFromBackend(managementId);
    // approvalRecords.value = response.data || [];
    
    // 临时：添加一些测试数据
    approvalRecords.value = [
      {
        id: 1,
        stepId: 1,
        stepName: '申请入住',
        approver: 'liuzhuo',
        approverRole: '入住养老顾问',
        approvalResult: '审批通过',
        approvalComment: '资料完整，老人基本信息已核实，可以进入下一步评估',
        approvalTime: '2024-10-20 10:30:00',
        formData: { basicForm, familyForm }
      },
      {
        id: 2,
        stepId: 2,
        stepName: '入住评估',
        approver: 'zihao',
        approverRole: '入住护理组部长',
        approvalResult: '审批通过',
        approvalComment: '评估完成，老人健康状况良好，能力等级为二级',
        approvalTime: '2024-10-20 14:15:00',
        formData: { healthForm, abilityForm, assessmentResults }
      }
    ];
    
    console.log("✅ 审批记录加载成功，共", approvalRecords.value.length, "条");
  } catch (error) {
    console.error("❌ 加载审批记录失败:", error);
  }
};

</script>

<style scoped>
.elderly-admission-system {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 主内容区域 */
.main-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

/* 步骤导航 */
.steps-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.step-item {
  display: flex;
  align-items: center;
  flex: 1;
  position: relative;
  cursor: pointer;
}

.step-item:last-child {
  flex: none;
}

.step-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f56c6c;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 14px;
  transition: all 0.3s ease;
  z-index: 2;
}

.step-item.active .step-number {
  background-color: #409eff;
}

.step-item.completed .step-number {
  background-color: #67c23a;
}

.step-label {
  margin-left: 8px;
  color: #c0c4cc;
  font-size: 14px;
  transition: color 0.3s ease;
}

.step-item.active .step-label {
  color: #409eff;
  font-weight: bold;
}

.step-item.completed .step-label {
  color: #67c23a;
}

/* 🔥【新增】禁用状态样式 */
.step-item.disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.step-item.disabled .step-number {
  background-color: #dcdfe6;
}

.step-item.disabled .step-label {
  color: #c0c4cc;
}

.step-connector {
  flex: 1;
  height: 2px;
  background-color: #e4e7ed;
  margin: 0 20px;
  transition: background-color 0.3s ease;
}

.step-item.active .step-connector {
  background-color: #409eff;
}

.step-item.completed .step-connector {
  background-color: #67c23a;
}

/* 操作记录 */
.operation-records {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-records h4 {
  margin-bottom: 15px;
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.record-content {
  flex: 2;
  color: #666;
}

.record-time {
  flex: 1;
  text-align: center;
  color: #999;
}

.record-status {
  flex: 1;
  text-align: right;
  color: #67c23a;
}

/* 步骤内容 */
.step-content {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.panel-header {
  padding: 30px 30px 0;
  text-align: center;
  position: relative;
}

.panel-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

/* 🔥 自动保存状态显示 */
.auto-save-status {
  position: absolute;
  right: 30px;
  top: 30px;
  display: flex;
  align-items: center;
  gap: 12px;
  z-index: 10;
}

.save-time {
  font-size: 13px;
  color: #67c23a;
  display: inline-flex;
  align-items: center;
  padding: 4px 12px;
  background: #f0f9ff;
  border-radius: 4px;
  border: 1px solid #e1f3d8;
  font-weight: 500;
}

.save-time::before {
  content: "✓";
  margin-right: 6px;
  font-weight: bold;
  font-size: 14px;
}

/* 标签页导航 */
.tab-navigation {
  display: flex;
  justify-content: center;
  margin: 30px 0;
  border-bottom: 1px solid #e4e7ed;
}

.tab-item {
  display: flex;
  align-items: center;
  padding: 15px 30px;
  cursor: pointer;
  border-bottom: 3px solid transparent;
  margin-bottom: -1px;
  transition: all 0.3s ease;
}

.tab-item.active {
  border-bottom-color: #409eff;
  background-color: #f0f7ff;
}

.tab-item:hover {
  background-color: #f5f7fa;
}

.upload-container {
  margin-bottom: 20px;
}

.uploaded-file-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-width: 200px;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.upload-sections {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.tab-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #f56c6c;
  color: white;
  font-size: 12px;
  margin-right: 8px;
}

.tab-item.active .tab-number {
  background-color: #409eff;
}

.tab-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.tab-item.active .tab-label {
  color: #409eff;
  font-weight: 600;
}

/* 标签页内容 */
.tab-content {
  padding: 0 30px 30px;
}

.tab-panel-content {
  min-height: 400px;
}

.basic-form {
  margin-top: 20px;
}

.family-table {
  margin-top: 20px;
}

.upload-notice {
  text-align: center;
  color: #999;
  margin-bottom: 30px;
}

.upload-sections {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.upload-item {
  display: flex;
  align-items: flex-start;
  gap: 30px;
}

.upload-label {
  width: 120px;
  padding-top: 8px;
  font-size: 14px;
}

.required {
  color: #f56c6c;
  margin-right: 4px;
}

/* 评估相关样式 */
.assessment-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.assessment-section h4 {
  margin-bottom: 15px;
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

.assessment-question {
  margin-bottom: 25px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.assessment-question h4 {
  margin-bottom: 10px;
  color: #333;
}

.assessment-report {
  padding: 20px;
}

.result-section {
  margin-bottom: 30px;
}

.score-card {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #f8f9fa;
}

.score-card h5 {
  margin-bottom: 10px;
  color: #333;
}

.scores span {
  display: block;
  margin-bottom: 5px;
  color: #666;
}

.total-score {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  text-align: center;
}

.level-result {
  margin-top: 15px;
  padding: 10px;
  background: #f0f7ff;
  border-radius: 4px;
}

.level-result span {
  display: block;
  margin-bottom: 5px;
  color: #333;
}

.change-basis,
.final-level {
  margin-bottom: 25px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.change-basis h4,
.final-level h4 {
  margin-bottom: 10px;
  color: #333;
}

/* 审批面板 */
.approval-panel {
  padding: 40px;
  text-align: center;
}

.approval-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
}

.status-text h4 {
  
  color: #e6a23c;
  margin-bottom: 10px;
}

.status-text p {
  color: #666;
}

/* 审批结果布局样式 */
.approval-result-container {
  display: flex;
  gap: 20px;
  text-align: left;
}

.approval-info-section,
.approval-actions-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
}

.info-card h4 {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 15px 0;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 8px;
  text-align: left;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  width: 100px;
  flex-shrink: 0;
}

.info-item .value {
  color: #303133;
  flex: 1;
}

/* 疾病列表样式 */
.disease-list {
  margin: 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.disease-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 审批结果选项样式 */
.approval-radio-group {
  margin-bottom: 15px;
}

.approval-radio-group .el-radio {
  display: block;
  margin-bottom: 10px;
}

.approval-comment label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

/* 操作记录样式 */
.operation-list {
  max-height: 300px;
  overflow-y: auto;
}

.operation-item {
  padding: 10px;
  background: white;
  border-radius: 4px;
  margin-bottom: 8px;
  border-left: 3px solid #409eff;
}

.operation-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.operation-action {
  color: #303133;
}

/* 配置内容 */
.configuration-content {
  padding: 20px;
}

.config-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.config-section h4 {
  margin-bottom: 15px;
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

.fee-notice {
  color: #999;
  margin-bottom: 15px;
  font-size: 14px;
}

/* 合同内容 */
.contract-content {
  padding: 20px;
}

.contract-section {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.contract-section h4 {
  margin-bottom: 15px;
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

/* 床位信息样式 */
.bed-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selected-bed {
  font-weight: 500;
  color: #409eff;
  margin-left: 10px;
  padding: 5px 10px;
  background-color: #ecf5ff;
  border-radius: 4px;
}

/* 床位选择对话框样式 */
.bed-selection {
  padding: 10px 0;
  max-height: 600px;
  overflow-y: auto;
}

.bed-building {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.bed-building h4 {
  margin-bottom: 15px;
  color: #303133;
  font-weight: 600;
  font-size: 16px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.room-section {
  margin-bottom: 15px;
  padding: 12px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.room-title {
  margin-bottom: 10px;
  color: #606266;
  font-weight: 500;
  font-size: 14px;
}

.bed-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
}

.bed-item {
  display: block;
}

.bed-list .el-radio {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 10px 12px;
  background-color: #f9fafc;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.3s;
}

.bed-list .el-radio:hover:not(.is-disabled) {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.bed-list .el-radio.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.bed-name {
  margin-right: 8px;
  font-weight: 500;
}

.bed-status-tag {
  margin-left: auto;
}

.empty-hint {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
}

.bed-list .el-radio:hover {
  background-color: #ecf5ff;
}

.bed-list .el-radio.is-checked {
  background-color: #ecf5ff;
  border: 1px solid #409eff;
}

/* 合同文件上传样式 */
.contract-content .el-upload {
  margin-top: 10px;
}

.contract-content .el-upload-list {
  margin-top: 10px;
}

/* PDF预览样式 */
.pdf-preview-container {
  height: calc(80vh - 100px);
  display: flex;
  flex-direction: column;
}

.pdf-info {
  margin-bottom: 20px;
}

.pdf-info h3 {
  margin-bottom: 10px;
  color: #303133;
}

.pdf-info p {
  color: #606266;
  font-size: 14px;
  margin-bottom: 15px;
}

.pdf-placeholder {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 40px;
  min-height: 300px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 床位选择 */
.bed-selection {
  min-height: 300px;
}

/* 账单预览样式 */
.bill-preview-content {
  padding: 20px;
}

.bill-header {
  margin-bottom: 20px;
  text-align: center;
}

.bill-header h3 {
  margin-bottom: 15px;
  color: #303133;
}

.bill-info {
  text-align: left;
  margin-bottom: 20px;
}

.bill-info .label {
  color: #606266;
  margin-right: 10px;
}

.bill-details {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.bill-row {
  display: flex;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.bill-row:last-child {
  border-bottom: none;
}

.bill-header-row {
  background-color: #f5f7fa;
  font-weight: 500;
}

.bill-total-row {
  font-weight: 600;
  color: #ff6700;
  background-color: #fff3e0;
}

.bill-col {
  flex: 1;
}

.bill-col:last-child {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .steps-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .step-item {
    width: 100%;
    margin-bottom: 15px;
  }

  .step-connector {
    display: none;
  }

  .tab-navigation {
    flex-direction: column;
  }

  .record-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .record-time,
  .record-status {
    text-align: left;
    margin-top: 5px;
  }

  .upload-item {
    flex-direction: column;
    gap: 15px;
  }

  .upload-label {
    width: 100%;
  }

  .approval-status {
    flex-direction: column;
    text-align: center;
  }
}

/* 合同文件展示样式 */
.existing-file {
  margin-bottom: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 8px;
}

.file-item .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.file-name {
  flex: 1;
  margin-right: 12px;
  color: #303133;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

/* 🔥【新增】审批记录样式 */
.approval-records-list {
  max-height: 500px;
  overflow-y: auto;
}

.approval-record-item {
  padding: 15px;
  margin-bottom: 12px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.approval-record-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.record-step {
  font-weight: 600;
  color: #303133;
}

.record-time {
  font-size: 12px;
  color: #909399;
}

.record-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.record-approver {
  color: #606266;
  font-size: 14px;
}

.record-result {
  margin-left: 10px;
}

.record-comment {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
  margin-top: 8px;
}

.record-comment .el-icon {
  margin-top: 2px;
  flex-shrink: 0;
}

.record-action-hint {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  font-size: 12px;
  color: #409eff;
  opacity: 0;
  transition: opacity 0.3s;
}

.approval-record-item:hover .record-action-hint {
  opacity: 1;
}

/* 审批记录详情弹窗样式 */
.approval-record-detail {
  padding: 10px 0;
}

.record-info-card,
.record-data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-snapshot {
  padding: 10px;
}

.snapshot-content {
  margin-top: 15px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  max-height: 400px;
  overflow: auto;
}

.snapshot-content pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.6;
  color: #606266;
}

.record-actions {
  text-align: center;
  padding: 15px 0;
}
</style>